简单的flask实例
hello world
from flask import Flask
app=Flask(__name__)
@app.route('/')
def hello_world():
return "flask is running"
if __name__ == "__main__":
app.run()
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
关于路由与变量
from flask import Flask
app=Flask(__name__)
@app.route('/')
def hello_world():
return "flask is running"
@app.route('/user/<username>/') #这里的username是一个路由上的变量
def show_user_name(username):
return "User:%s" % username
if __name__ == '__main__':
app.run(debug=True)
get post方法判断
from flask import Flask
from flask import request
app=Flask(__name__)
@app.route('/')
def hello_world():
return "flask is running"
@app.route('/project/',methods=['GET','POST'])
def method():
if request.method == 'POST':
return 'method : post'
else:
return 'method : get'
if __name__ == '__main__':
app.run(debug=True)
模版的使用
@app.route('/hello/<name>/')
def hello_world(name=None):
return render_template('first.html',name=name)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>flask</title>
</head>
<body>
{% if name %}
<h1>Hello {{name}}!</h1>
{% else %}
<h1>on name</h1>
{% endif %}
</body>
</html>
路由重定向
@app.route('/hello/<name>/')
def hello_world(name=None):
return render_template('first.html',name=name)
@app.route('/a')
def refirect():
return redirect('/hello/admin')
post/get方法获取返回值
@app.route('/project/',methods=['GET','POST'])
def project():
if request.method=='POST':
name=request.form.get('name','aa')
age=request.form.get('age','bb')
return name+'is'+age
else:
shots=request.args.get('string','test_string')
return str(shots)
import requests
a=requests.get('http://127.0.0.1:5000/project/')
print(a.text)
data={'name':'admin','age':'24'}
b=requests.post('http://127.0.0.1:5000/project/',data=data)
print(b.text)
test_string
adminis24