Markdownpad Document
Python Flask Tutorials
Example 1:
import flaskfrom flask import *app=Flask(__name__) #创建新的开始@app.route(‘/‘) #路由设置def imdex(): #如果访问了/则调用下面的局部变量 return ‘Post qingqiu !‘ #输出if __name__ == ‘__main__‘: app.run() #运行开始
Visit: 127.0.0.1:5000/
Results:
Request method
Example 2:
import flaskfrom flask import *app=Flask(__name__)#flask.request为请求方式@app.route(‘/‘,methods=[‘GET‘,"POST"]) #mthods定义了请求的方式def imdex(): if request.method==‘POST‘: #判断请求 return ‘Post qingqiu !‘ else: return ‘Get qinqiu !‘if __name__ == ‘__main__‘: app.run()
The result returned by the GET request is as follows:
The POST request is as follows:
Template rendering
Create a Templates folder in the same directory, and then put inside the file you want to call
of HTML. Use Render_template (' HTML to invoke ')
Example 3:
import flaskfrom flask import *app=Flask(__name__)@app.route(‘/‘,methods=[‘GET‘,"POST"])def imdex(): if request.method==‘POST‘: return ‘Post qingqiu !‘ else: return render_template(‘index.html‘) #调用htmlif __name__ == ‘__main__‘: app.run()
Index.html Code:
<!DOCTYPE html>
Results:
Dynamic version RenderingPersonally think, this should be less used, after all, is this:/path/Parameters
Example:
import flaskfrom flask import *app=Flask(__name__)@app.route(‘/index‘)@app.route(‘/index/<name>‘) #html里面的参数为name这里也为name动态摸版调用def index(name): #html里面的参数为name这里也为name return render_template(‘index.html‘,name=name) #调用if __name__ == ‘__main__‘: app.run()
HTML code:
<!DOCTYPE html>
Results:
Accept Request ParametersExample:
Request.Form. Request method (' Data name ' in the form ') #用于接受表单传来的数据
import flaskfrom flask import *app=Flask(__name__)@app.route(‘/index/<name>‘)def index(name): return render_template(‘index.html‘,name=name)@app.route(‘/login‘,methods=[‘GET‘,‘POST‘]) #可使用的请求有GET和POSTdef login(): error=None if request.method=="GET": #如果请求为GET打开login.html return render_template(‘login.html‘) else: username=request.form.get(‘username‘) #获取表单里的username数据 password=request.form.get(‘password‘) #获取表单里的password数据 if username==‘admin‘ and password==‘admin‘: #判断表单里的username和password数据是否等于admin return ‘login ok‘ #如果是则返回登录成功if __name__ == ‘__main__‘: app.run()
HTML code:
Here {{url_for (' login ')}} #代表着发送数据
<!DOCTYPE html>
The results are as follows
Enter Admin admin
Returns the following
Python Flask Chapter (i)