Flask 的常用模块和命令

本文最后更新于:July 27, 2024 8:58 PM

本健忘症晚期患者自用

模块

Basebones App

1
2
3
4
5
6
7
8
9
from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello():
return 'Hello, World!'

if __name__ == '__main__':
app.run(debug=True)

Routing

1
2
3
@app.route('/hello/<string:name>, methods=['GET', 'POST'])
def hello(name):
return 'Hello ' + name + '!'

Templates

1
return render_template('template_file.html', val1 = value1, ...)

JSON Responses

1
2
3
4
5
6
7
8
import jsonify

@app.route('/returnstuff')
def returnstuff():
num_list = [1,2,3,4,5]
num_dict = {'numbers' : num_list, 'name' : 'Numbers'}
#returns {'output' : {'numbers' : [1,2,3,4,5], 'name' : 'Numbers'}}
return jsonify({'output' : num_dict})

Access Request Data

1
2
3
4
5
request.args['name'] #query string arguments
request.form['name'] #form data
request.method #request type
request.cookies.get('cookie_name') #cookies
request.files['name'] #files

Redirect

1
return redirect(url_for('index'))

命令

Create virtual environment locally

1
virtualenv env

Activate virtual environment

1
source env/Scripts/activate

Create database

1
2
3
$ python
>>> from app import db
>>> db.create_all()

部署

用的 Heroku

Freeze requirements

1
pip freeze > requirements.txt

Procile

1
web: gunicorn app:app

Get postgresql

1
heroku addons:create heroku-postgresql:hobby-dev --app [appname]

Get datatbase url

1
heroku conig --app [appname] 

Remember to change postgres://... to postgresql://...