在计算机应用中,HTTP协议是互联网中数据通信的基础,在现实应用中,常用的两种传递HTTP请求的方法是GET和POST。在Flask框架中,默认使用GET方法。通过使用URL装饰器的参数“方法类型”,可以让同一个URL的两种请求方法都映射在同一个函数上。接下来我们上两个实例:
一、使用GET请求获取URL参数。
importflask#变量html_txt初始化,作为GET请求的页面html_txt="""!DOCTYPEhtmlhtmlbodyh2当收到GET请求时/h2!设置请求方法为POSTformmethod=postinputtype=submitvalue=点击发送POST请求//form/body/html"""app=flask.Flask(__name__)#URL映射,将GET方法和POST方法都映射到qingqiu函数
app.route(/abc,methods=[GET,POST])defqingqiu():#如果收到的请求是GETifflask.request.method==GET:#返回html_txt的页面内容returnhtml_txt#否则返回:post请求已收到!else:returnPOST请求已收到!if__name__==__main__:app.run(debug=True)浏览器中输入地址,如下图:
点击按钮发送POST请求,得到响应如下图:
二、使用重定向的方法处理URL请求。
fromflaskimportFlask,redirect,url_forapp=Flask(__name__)
app.route(/yuangong)defhello_yuangong():return你好,工作人员!app.route(/guest/guest)defhello_guest(guest):return欢迎游客:%s!%guestapp.route(/user/name)defhello_user(name):ifname==yuangong:returnredirect(url_for(hello_yuangong))else:returnredirect(url_for(hello_guest,guest=name))if__name__==__main__:app.run(debug=True)浏览器中输入