From:http://docs.jinkan.org/docs/flask/quickstart.html
Flask 用户指南:http://docs.jinkan.org/docs/flask/index.html
w3cschool.cn 的 Flask 教程:https://www.w3cschool.cn/flask/
《Flask Web开发:基于Python的Web应用开发实战》第2版中文PDF,324页,带书签目录,文字能够复制粘贴;配套源代码;
下载: https://pan.baidu.com/s/1qhCaPeX41vltmeI-XFVLIA 提取码: v9w5
Flask大型教程项目:http://www.pythondoc.com/flask-mega-tutorial/index.html#
依赖:
pip install flask
from flask import Flask,url_for,request,render_template app = Flask(__name__)
@app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': if request.form['user'] == 'admin': return 'Admin login successfully!' else: return 'No such user!' user = request.args.get('user', 'Default') # get request args return render_template('login.html', user=user) if __name__ == "__main__":
app.run(host='0.0.0.0',port=8090, debug=True)
# post json @app.route('/shopees', methods=['POST']) def jsondata(): if request.method == 'POST': data = json.loads(request.get_data(as_text=True)) print("data ", data) # chromeRequest() return {}
代码示例:
from flask import Flask from flask import request from werkzeug import utils import json; app = Flask(__name__) @app.route('/', methods=['POST']) def hello_world(): return 'Hello World!' # app.logger.addHandler(handler) @app.route('/hello') def hello_world1(): app.logger.info('enter into hello world'); return 'Hello World1!' @app.route('/upload', methods=['GET', 'POST']) def upload_file(): app.logger.info("request is {}", request.json); if request.method == 'POST': utils.secure_filename() f = request.files['the_file']; # f.save('/var/www/uploads/uploaded_file.txt') return "the file upload successfully"; else: return "the file upload failed"; @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': str = request.get_json(force=True) username = str.get("username") app.logger.info("str is {}" + username); json1 = {"data":username} return json.dumps(json1); if __name__ == '__main__': app.run(debug=True)
外部可访问的服务器
如果你运行了这个服务器,你会发现它只能从你自己的计算机上访问,网络中其它任何的地方都不能访问。在调试模式下,用户可以在你的计算机上执行任意 Python 代码。因此,这个行为是默认的。
如果你禁用了 debug 或信任你所在网络的用户,你可以简单修改调用 run() 的方法使你的服务器公开可用,如下:
app.run(host='0.0.0.0')