Python Flask教程学习01

教程来源于w3cschool,我跟着敲一遍,做一遍

Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容易上手。它可以很好地结合MVC模式进行开发,开发人员分工合作,小型团队在短时间内就可以完成功能丰富的中小型网站或Web服务的实现。另外,Flask还有很强的定制性,用户可以根据自己的需求来添加相应的功能,在保持核心功能简单的同时实现功能的丰富与扩展,其强大的插件库可以让用户实现个性化的网站定制,开发出功能强大的网站。

Flask 教程

Flask 应用

from flask import Flask
app=Flask(__name__)

@app.route('/')
'''
app.route(rule,options)
rule 参数表示与该函数的URL绑定。
options 是要转发给基础Rule对象的参数列表。
在上面的示例中,'/ ' URL与hello_world()函数绑定。
因此,当在浏览器中打开web服务器的主页时,将呈现该函数的输出。
最后,Flask类的run()方法在本地开发服务器上运行应用程序。
'''
def hello_world():
    return 'Hello World'
if __name__ == '__main__':
    app.run()
    #app.run(host, port, debug, options)

cmd命令行运行python xxx.py
打开http://127.0.0.1:5000/会显示Hello World

Flask 路由

@app.route('/hello')
def hello_world():
    return 'hello world'

打开http://127.0.0.1:5000/hello会显示hello world

Flask 变量规则

通过向规则参数添加变量部分,可以动态构建URL。
此变量部分标记为

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/Flask显示Hello Flask!

from flask import Flask
app=Flask(__name__)
@app.route('/blog/<int:postID>')
def show_blog(postID):
    return 'Blog Number %d' % postID
@app.route('/rev/<float:revNo>')
def revision(revNo):
    return 'Revision Number %f' % revNo
if __name__ == '__main__':
    app.run()

打开http://localhost:5000/blog/55显示Blog Number 55
打开http://localhost:5000/rev/1.5显示Revision Number 1.500000

from flask import Flask
app=Flask(__name__)
@app.route('/flask')
def hello_flask():
    return 'Hello Flask'
@app.route('/python/')
def hello_python():
    return 'Hello Python'
if __name__ == '__main__':
    app.run()

打开http://localhost:5000/flask显示Hello Flask
打开http://localhost:5000/flask/显示404 Not Found
打开http://localhost:5000/pythonhttp://localhost:5000/python/都显示Hello Python

Flask URL构建

url_for()函数对于动态构建特定函数的URL非常有用。
url_for()函数接受函数的名称作为第一个参数,以及一个或多个关键字参数,每个参数对应于URL的变量部分。

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)

打开http://localhost:5000/admin显示Hello Admin
打开http://localhost:5000/guest/xwk显示Hello xwk as Guest

Flask HTTP方法

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>
from flask import Flask,redirect,url_for,request,render_template
app=Flask(__name__)

@app.route('/')
def index():
    return render_template("login.html")

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

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

打开login.html
在这里插入图片描述
提交姓名后跳转至http://localhost:5000/success/xwk并显示welcome xwk

在login.html中将方法参数更改为’get’
跳转后输出内容一样

Flask 模板

模板基本使用
在项目下创建 templates 文件夹,用于存放所有模板文件,并在目录下创建一个模板文件 html 文件 hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
我的模板html内容
<br />{
   
   { my_str }}
<br />{
   
   { my_int }}
<br />{
   
   { my_array }}
<br />{
   
   { my_dict }}
</body>
</html>
from flask import Flask,render_template
app=Flask(__name__)

#创建视图函数,将该模板内容进行渲染返回
@app.route('/')
def index():
    # 往模板中传入的数据
    my_str = 'Hello Word'
    my_int = 10
    my_array = [3, 4, 2, 1, 7, 9]
    my_dict = {
    
    
        'name': 'xiaoming',
        'age': 18
    }
    return render_template('hello.html',
                          my_str=my_str,
                           my_int=my_int,
                           my_array=my_array,
                           my_dict=my_dict
                           )
#模板变量
#代码中传入字符串,列表,字典到模板中


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

打开http://127.0.0.1:5000/内容为

我的模板html内容
Hello Word
10
[3, 4, 2, 1, 7, 9]
{
    
    'name': 'xiaoming', 'age': 18}

Flask 静态文件

Web应用程序通常需要静态文件,例如javascript文件或支持网页显示的CSS文件。

demo01.py

from flask import Flask,render_template
app=Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

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

templates文件夹下的index.html

<html>
   <head>
   <script type = "text/javascript" src = "{
     
     { url_for('static', filename = 'hello.js') }}" ></script>
   </head>
   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
</html>

static文件夹中下的hello.js

function sayHello(){
    
    
	alert("Hello World")
}

http://127.0.0.1:5000/
在这里插入图片描述

Flask Request对象

Request对象的重要属性如下所列:

  • Form -它是一个字典对象,包含表单参数及其值的键和值对。
  • args -解析查询字符串的内容,它是问号(?)之后的URL的一部分
  • Cookies -保存Cookie名称和值的字典对象。
  • fules -与上传文件有关的数据
  • method -当前请求方法

Flask 将表单数据发送到模板

from flask import Flask,render_template,request
app=Flask(__name__)

@app.route('/')
def student():
    return render_template('student.html')
@app.route('/result',methods=['POST','GET'])
def result():
	if request.method=='POST':
		result=request.form
		return render_template('result.html',result=result)
if __name__ == '__main__':
    app.run(debug=True)

student.html

<form action="http://localhost:5000/result" method="POST">
     <p>Name <input type = "text" name = "Name" /></p>
     <p>Physics <input type = "text" name = "Physics" /></p>
     <p>Chemistry <input type = "text" name = "chemistry" /></p>
     <p>Maths <input type ="text" name = "Mathematics" /></p>
     <p><input type = "submit" value = "submit" /></p>
</form>

result.html

<!doctype html>
  <table border = 1>
     {% for key, value in result.items() %}
    <tr>
       <th> {
   
   { key }} </th>
       <td> {
   
   { value }}</td>
    </tr>
 {% endfor %}
</table>

在这里插入图片描述
在这里插入图片描述

Flask Cookies

from flask import Flask,make_response,request
app=Flask(__name__)

@app.route('/set_cookies')
def set_cookies():
    resp=make_response("success")#设置响应体
    resp.set_cookie("xwk","xwk",max_age=3600)#max_age设置有效期,单位为秒
    return resp
@app.route('/get_cookies')
def get_cookies():
    #获取cookie,通过request.cookies的方式,返回的是一个字典,可以获取字典里的相应的值
    cookie_1=request.cookies.get("xwk")#获取名字为Itcast_1对应cookie的值
    return cookie_1
@app.route('/delete_cookies')
def delete_cookie():
    resp=make_response("del success")
    #这里的删除只是让cookie过期,并不是直接删除cookie
    resp.delete_cookie("xwk")
    return resp
if __name__ == '__main__':
    app.run(debug=True)

http://localhost:5000/set_cookies
F12这个页面如果没有如下显示,刷新一下页面就行
在这里插入图片描述
http://localhost:5000/get_cookies
你设置的什么就显示什么

http://localhost:5000/delete_cookies
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46322367/article/details/127502253
今日推荐