码迷,mamicode.com
首页 > 编程语言 > 详细

初识Flask——基于python的web框架

时间:2020-05-09 21:35:42      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:rgs   orm   注意   准备   lse   现在   tran   mic   python3   

参考教程链接:

1.https://dormousehole.readthedocs.io/en/latest/

2.https://www.w3cschool.cn/flask/

 

前提准备:anaconda(python3),pycharm

一、写一个hello.py

from flask import Flask
app = Flask(__name__)

@app.route(/)
def hello_world():
   return Hello World’

if __name__ == __main__:
   app.run()

解释:

1.@app.route(‘/‘)说明了下面的hello_world()函数与url‘/‘绑定(http://127.0.0.1:5000/)
运行该hello.py,点击pycharm下的链接http://127.0.0.1:5000/,即会显示字符串Hello World
2.@app.route(‘/hello’)则绑定http://localhost:5000/hello

二、从url名字传递参数(
@app.route(‘/hello/<name>‘)
from flask import Flask
app = Flask(__name__)

@app.route(/hello/<name>)
def hello_name(name):
   return Hello %s! % name

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

输入链接:http:// localhost:5000/hello/Jack


将会显示: Hello Jack!

参考:https://www.w3cschool.cn/flask/flask_variable_rules.html

 

三、url重定向(return redirect(url_for(‘hello_admin‘)))

url_for(‘‘)  #重定向到另外一个函数

from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route(/admin)
def hello_admin():
   return Hello Admin


@app.route(/guest/<guest>)

def hello_guest(guest):
   return Hello %s as Guest % guest


@app.route(/user/<name>)
def hello_user(name):
   if name ==admin:
      return redirect(url_for(hello_admin))
   else:
      return redirect(url_for(hello_guest,guest = name))


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

打开浏览器并输入URL - http://localhost:5000/user/admin

浏览器中的应用程序响应是:

Hello Admin

在浏览器中输入以下URL - http://localhost:5000/user/mvl

应用程序响应现在更改为:

Hel
lo mvl as Guest

 四、结合html和post和get

将以下脚本另存为login.html

<html>
   <body>
      
      <form action = "http://localhost:5000/login" method = "post">
         <p>Enter Name:</p>
         <p><input type = "text" name = "nm" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
      
   </body>
</html>

hello.py如下:

from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route(/success/<name>)
def success(name):
   return welcome %s % name

@app.route(/login,methods = [POST, GET])
def login():
   if request.method == POST:
      user = request.form[nm]
      return redirect(url_for(success,name = user))
   else:
      user = request.args.get(nm)
      return redirect(url_for(success,name = user))

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

注意到,form表单method是post,input框的name是‘nm‘

<p><input type = "text" name = "nm" /></p>

在本地打开文件login.html

技术图片

 

summit以后,网页自动跳转到‘/ success‘ URL,显示:welcome mvl

 

 

初识Flask——基于python的web框架

标签:rgs   orm   注意   准备   lse   现在   tran   mic   python3   

原文地址:https://www.cnblogs.com/qiezi-online/p/12859820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!