项目结构

Flask框架 - 图1

第一个Flask程序

示例代码

  1. from flask import Flask
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def hello_world():
  5. return 'Hello World!'
  6. if __name__ == '__main__':
  7. app.run()

开启debug模式

Flask框架 - 图2

加载配置文件

示例代码如下

  1. from flask import Flask
  2. import config
  3. app = Flask(__name__)
  4. app.config.from_object(config)
  5. @app.route('/')
  6. def hello_world():
  7. return {
  8. 'name': '逍遥子',
  9. 'age': 18
  10. }
  11. if __name__ == '__main__':
  12. app.run()

参数传递

方式一

  1. @app.route("/user/<uid>")
  2. def user_info(uid):
  3. return "当前用户是:" + uid

方式二

  1. from flask import request
  2. @app.route("/user")
  3. def user_info():
  4. uid = request.args.get("uid")
  5. return "当前用户是:" + uid

请求方式

指定请求方式

  1. @app.route("/user", methods=["GET"])
  2. def user_info():
  3. uid = request.args.get("uid")
  4. return "当前用户是:" + uid

url_for

视图函数与url之间的映射

  1. @app.route("/user")
  2. def user_info():
  3. uid = request.args.get("uid")
  4. print(url_for("user_info")) # /user
  5. return "当前用户是:" + uid

重定向

永久性重定向:状态码301

临时性重定向:状态码302

  1. from flask import Flask, request, url_for, redirect
  2. @app.route('/')
  3. def hello_world():
  4. return 'Hello World!'
  5. @app.route("/user")
  6. def user_info():
  7. # 跳转到首页
  8. return redirect(url_for("hello_world"))

七牛云存储

1、后台接口编写

  1. @app.route('/uptoken/')
  2. def uptoken():
  3. access_key = 'Uxv7S8cYoVvzznmVcWegxzV-ihWvqjDR5iV3Joph'
  4. secret_key = 'jM_VBuv9TODxZ0M1F5hPUtYkyGhjutKQXzRSe93Q'
  5. q = qiniu.Auth(access_key,secret_key)
  6. bucket = 'dxzlk'
  7. token = q.upload_token(bucket)
  8. return {"uptoken": token}

2、前端上传接口编写

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="https://cdn.staticfile.org/Plupload/2.1.1/moxie.js"></script>
  7. <script src="https://cdn.staticfile.org/Plupload/2.1.1/plupload.dev.js"></script>
  8. <script src="https://cdn.staticfile.org/qiniu-js-sdk/1.0.14-beta/qiniu.js"></script>
  9. <!-- 七牛封装代码 -->
  10. <script src="{{ url_for('static',filename='gmqiniu.js') }}"></script>
  11. </head>
  12. <body>
  13. <button id="upload-btn">上传文件</button>
  14. <input type="text" id="image-input">
  15. <img src="" alt="" id="img">
  16. </body>
  17. <script>
  18. // 文件上传
  19. window.onload = function () {
  20. gmqiniu.setUp({
  21. 'domain': 'http://gmbjzg.top/',
  22. 'browse_btn': 'upload-btn',
  23. 'uptoken_url': '/uptoken/',
  24. 'success': function (up,file,info) {
  25. var url = file.name;
  26. document.getElementById('image-input').value = url;
  27. }
  28. });
  29. };
  30. </script>
  31. </html>

注意事项:绑定自已的域名需要在域名提供商添加一条CNAME记录