项目结构
第一个Flask程序
示例代码
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
开启debug模式
加载配置文件
示例代码如下
from flask import Flask
import config
app = Flask(__name__)
app.config.from_object(config)
@app.route('/')
def hello_world():
return {
'name': '逍遥子',
'age': 18
}
if __name__ == '__main__':
app.run()
参数传递
方式一
@app.route("/user/<uid>")
def user_info(uid):
return "当前用户是:" + uid
方式二
from flask import request
@app.route("/user")
def user_info():
uid = request.args.get("uid")
return "当前用户是:" + uid
请求方式
指定请求方式
@app.route("/user", methods=["GET"])
def user_info():
uid = request.args.get("uid")
return "当前用户是:" + uid
url_for
视图函数与url之间的映射
@app.route("/user")
def user_info():
uid = request.args.get("uid")
print(url_for("user_info")) # /user
return "当前用户是:" + uid
重定向
永久性重定向:状态码301
临时性重定向:状态码302
from flask import Flask, request, url_for, redirect
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route("/user")
def user_info():
# 跳转到首页
return redirect(url_for("hello_world"))
七牛云存储
1、后台接口编写
@app.route('/uptoken/')
def uptoken():
access_key = 'Uxv7S8cYoVvzznmVcWegxzV-ihWvqjDR5iV3Joph'
secret_key = 'jM_VBuv9TODxZ0M1F5hPUtYkyGhjutKQXzRSe93Q'
q = qiniu.Auth(access_key,secret_key)
bucket = 'dxzlk'
token = q.upload_token(bucket)
return {"uptoken": token}
2、前端上传接口编写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/Plupload/2.1.1/moxie.js"></script>
<script src="https://cdn.staticfile.org/Plupload/2.1.1/plupload.dev.js"></script>
<script src="https://cdn.staticfile.org/qiniu-js-sdk/1.0.14-beta/qiniu.js"></script>
<!-- 七牛封装代码 -->
<script src="{{ url_for('static',filename='gmqiniu.js') }}"></script>
</head>
<body>
<button id="upload-btn">上传文件</button>
<input type="text" id="image-input">
<img src="" alt="" id="img">
</body>
<script>
// 文件上传
window.onload = function () {
gmqiniu.setUp({
'domain': 'http://gmbjzg.top/',
'browse_btn': 'upload-btn',
'uptoken_url': '/uptoken/',
'success': function (up,file,info) {
var url = file.name;
document.getElementById('image-input').value = url;
}
});
};
</script>
</html>
注意事项:绑定自已的域名需要在域名提供商添加一条CNAME
记录