python之flask安装以及使用

发布于:2024-04-23 ⋅ 阅读:(15) ⋅ 点赞:(0)

1 flask介绍

Flask是一个非常小的Python Web框架,被称为微型框架;只提供了一个稳健的核心,其他功能全部是通过扩展实现的;意思就是我们可以根据项目的需要量身定制,也意味着我们需要学习各种扩展库的使用。

2 python虚拟环境搭建

python虚拟环境管理方法:
​
1.virtualenv
2.Virtualenvwrapper
3.conda
4.pipenv

3 pipenv使用

┌──(kali㉿kali)-[~/Desktop/python_code]
└─$ ls       
flask1    
┌──(kali㉿kali)-[~/Desktop/python_code]
└─$ cd flask1                                         
┌──(kali㉿kali)-[~/Desktop/python_code/flask1]
└─$ pipenv shell    

┌──(flask1-l5Pm-i-x)─(kali㉿kali)-[~/Desktop/python_code/flask1]
└─$ ls
Pipfile
#Pipfile 等于安装的插件包名
┌──(flask1-l5Pm-i-x)─(kali㉿kali)-[~/Desktop/python_code/flask1]
└─$ cat Pipfile 
安装 flask
┌──(flask1-l5Pm-i-x)─(kali㉿kali)-[~/Desktop/python_code/flask1]
└─$ pipenv install flask
​

4 flask第一个应用

新建app.py

#!/usr/bin/env python3
​
from flask import Flask
​
#初始化
app =Flask(__name__)
​
@app.route('/')
def index():
    return  'Hello World!'
​
if __name__ == '__main__':
    app.run()

执行app.py

游览器效果

5 路由和视图函数

#!/usr/bin/env python3  
# 这一行告诉系统使用哪个解释器来执行脚本,这里指定为 python3  
  
from flask import Flask  
# 从flask模块中导入Flask类,用于创建Flask web应用程序实例  
  
# 初始化  
app = Flask(__name__)  
# 创建一个Flask应用程序实例,并赋值给变量app。__name__是当前模块的名字,代表应用程序的根路径  
  
# 设置多个路由  
@app.route('/')  
# 定义一个路由装饰器,当访问根路径'/'时,会调用下面的index函数  
def index():  
    return 'Hello World!'  
# 定义一个视图函数index,当访问'/'路径时,返回'Hello World!'字符串  
  
@app.route('/a')  
# 定义另一个路由装饰器,当访问'/a'路径时,会调用下面的add函数  
def add():  
    return '1+1=2'  
# 定义一个视图函数add,当访问'/a'路径时,返回'1+1=2'字符串  
  
@app.route('/user/<username>')  
# 定义一个带有动态部分的路由装饰器,'<username>'是一个动态部分,可以匹配任何字符串  
def user_index(username):  
    # 在函数中指明变量名称username,就能获取到通过路由传入的变量username  
    return 'Hello {} '.format(username)  
# 定义一个视图函数user_index,该函数接受一个参数username,这是从路由动态部分获取的。函数返回'Hello '加上用户名  
  
@app.route('/post/<int:post_id>')  
# 定义一个带有动态部分且类型指定的路由装饰器,'<int:post_id>'表示动态部分必须是整数类型  
def show_post(post_id):  
    return 'Post {} '.format(post_id)  
# 定义一个视图函数show_post,该函数接受一个整数类型的参数post_id,这是从路由动态部分获取的。函数返回'Post '加上文章ID  
  
if __name__ == '__main__':  
    # 判断当前脚本是否作为主程序运行  
    app.run(debug=True)  
​

6URL重定向

#!/usr/bin/env python3  
  
# 导入 Flask 框架  
from flask import Flask  
from flask import url_for  
from flask import redirect  
  
# 初始化 Flask 应用  
app = Flask(__name__)  
  
# 设置路由到根路径 '/'  
@app.route('/')  
def index():  
    return 'Hello World!'  # 返回欢迎信息  
  
# 设置路由到 '/a'  
@app.route('/a')  
def add():  
    return '1+1=2'  # 返回加法运算结果  
  
# 设置路由到 '/user/<username>',其中 <username> 是一个动态部分  
@app.route('/user/<username>')  
def user_index(username):  
    # 在视图函数中通过参数获取路由中的动态部分 username  
    return 'Hello {} '.format(username)  # 返回包含用户名的欢迎信息  
  
# 设置路由到 '/post/<int:post_id>',其中 <int:post_id> 是一个整数类型的动态部分  
@app.route('/post/<int:post_id>')  
def show_post(post_id):  
    return 'Post {} '.format(post_id)  # 返回包含帖子ID的字符串  
  
# 设置路由到 '/test'  
@app.route('/test')  
def test():  
    # 使用 url_for 函数生成路由的 URL,并打印出来  
    print(url_for('index'))  # 打印根路径的 URL  
    print(url_for('user_index', username='scj'))  # 打印用户路径的 URL,传入用户名 'scj'  
    print(url_for('show_post', post_id=1))  # 打印帖子路径的 URL,传入帖子ID 1  
    return 'test'  # 返回测试字符串  
  
# 设置路由到 '/<username>',其中 <username> 是一个动态部分  
@app.route('/<username>')  
def hello(username):  
    if username == 'handsomescj':  
        return 'Hello {}' .format(username)  # 如果用户名是 'handsomescj',则返回欢迎信息  
    else:  
        return redirect(url_for('index'))  # 否则重定向到根路径  
  
# 主程序入口  
if __name__ == '__main__':  
    app.run(debug=True)  # 运行 Flask 应用,并开启调试模式
​
请注意,代码中有个小的错误,app =Flask(__name__) 这一行应该去掉变量名 app 前的空格,修改为 app = Flask(__name__)。
​
在 Flask 应用中,注释是一个很好的习惯,它们可以帮助你和其他开发者理解代码的功能和逻辑。在编写代码时,记得添加足够的注释,尤其是在复杂的逻辑部分。

7模板渲染

python
#!/usr/bin/env python3  
  
# 导入 Flask 框架  
from flask import Flask  
from flask import url_for  
from flask import redirect  
from flask import render_template  
  
# 初始化 Flask 应用  
app = Flask(__name__)  
  
# 设置路由到根路径 '/'  
@app.route('/')  
def index():  
    return 'Hello World!'  # 返回欢迎信息  
  
# 设置路由到 '/a'  
@app.route('/a')  
def add():  
    return '1+1=2'  # 返回加法运算结果  
  
# 设置路由到 '/user/<username>',其中 <username> 是一个动态部分  
@app.route('/user/<username>')  
def user_index(username):  
    # 使用 render_template 函数渲染 'user_index.html' 模板,并传入变量 username  
    return render_template('user_index.html', username=username)  # 返回渲染后的页面  
  
# 设置路由到 '/post/<int:post_id>',其中 <int:post_id> 是一个整数类型的动态部分  
@app.route('/post/<int:post_id>')  
def show_post(post_id):  
    return 'Post {} '.format(post_id)  # 返回包含帖子ID的字符串  
  
# 设置路由到 '/test'  
@app.route('/test')  
def test():  
    # 使用 url_for 函数生成路由的 URL,并打印出来  
    print(url_for('index'))  # 打印根路径的 URL  
    print(url_for('user_index', username='scj'))  # 打印用户路径的 URL,传入用户名 'scj'  
    print(url_for('show_post', post_id=1))  # 打印帖子路径的 URL,传入帖子ID 1  
    return 'test'  # 返回测试字符串  
  
# 设置路由到 '/<username>',其中 <username> 是一个动态部分  
@app.route('/<username>')  
def hello(username):  
    if username == 'handsomescj':  
        return 'Hello {}' .format(username)  # 如果用户名是 'handsomescj',则返回欢迎信息  
    else:  
        return redirect(url_for('index'))  # 否则重定向到根路径  
  
# 主程序入口  
if __name__ == '__main__':  
    app.run(debug=True)  # 运行 Flask 应用,并开启调试模式
​

新建templates 文件夹

以及在templates 文件中新建user_index.html

<h1>hello,{{ username }}!</h1>

8 get与post请求

get请求

#!/usr/bin/env python3
​
from flask import Flask
from flask import url_for
from flask import redirect
from flask import render_template
​
#初始化
app =Flask(__name__)
​
#设置多个路由
@app.route('/')
def index():
    return  'Hello World!'
​
@app.route('/a')
def add():
    return  '1+1=2'
​
@app.route('/user/<username>')
def user_index(username):
    #在函数中指明变量名称username,就能获取到通过路由传入的变量username
    return render_template('user_index.html',username=username)
​
@app.route(' /user/<password>' )
def user_password(password) :
    print( 'User-Agent :' , request.headers.get ( 'User-Agent ' ))
    print( 'time: ' , request.args. get( 'time'))
    print( 'q: ' , request.args. get( 'q'))
    print ( 'issinge : ' , request.args.get( ' issinge ' ))
    return ' password is{} '.format(password)
​
@app.route('/post/<int:post_id>')
def show_post(post_id):
    return 'Post {} '.format(post_id)
​
@app.route('/test')
def test():
    print(url_for('index'))
    print(url_for('user_index',username='scj'))
    print(url_for('show_post',post_id=1))
    return 'test'
​
@app.route('/<username>')
def hello(username):
    if username =='handsomescj':
        return 'Hello {}' .format(username)
    else:
        return redirect(url_for('index'))
​
if __name__ == '__main__':
    app.run(debug=True)
​

post请求

#!/usr/bin/env python3  
  
from flask import Flask, request, render_template, redirect, url_for  
  
# 初始化  
app = Flask(__name__)  
  
# 设置多个路由  
@app.route('/')  
def index():  
    return 'Hello World!'  
  
@app.route('/a')  
def add():  
    return '1+1=2'  
  
@app.route('/user/<username>')  
def user_index(username):  
    # 在函数中指明变量名称username,就能获取到通过路由传入的变量username  
    return render_template('user_index.html', username=username)  
  
@app.route('/user/<password>')  
def user_password(password):  
    print('User-Agent:', request.headers.get('User-Agent'))  
    print('time:', request.args.get('time'))  
    print('q:', request.args.get('q'))  
    print('issinge:', request.args.get('issinge'))  
    return 'password is {}'.format(password)  
  
@app.route('/post/<int:post_id>')  
def show_post(post_id):  
    return 'Post {}'.format(post_id)  
  
@app.route('/test')  
def test():  
    print(url_for('index'))  
    print(url_for('user_index', username='scj'))  
    print(url_for('show_post', post_id=1))  
    return 'test'  
  
@app.route('/<username>')  
def hello(username):  
    if username == 'handsomescj':  
        return 'Hello {}'.format(username)  
    else:  
        return redirect(url_for('index'))  
  
@app.route('/register', methods=['GET', 'POST'])  
def register():  
    print('method:', request.method)  
    print('name:', request.form['name'])  
    print('password:', request.form.get('password'))  
    print('hobbies:', request.form.getlist('hobbies'))  
    print('age:', request.form.get('age', default=18))  
    return 'register success!'  
  
if __name__ == '__main__':  
    app.run(debug=True)
​

新建client.py

#!/usr/bin/env python3  
  
import requests  
  
# 设置需要发送的数据  
user_info = {  
    'name': 'scj',  # 去掉键和值之间的空格  
    'password': '123456',  # 去掉键和值之间的空格  
    'hobbies': ['code', 'run']  # 列表中的字符串去掉空格  
}  
  
# 向url发送post请求  
r = requests.post("http://127.0.0.1:5000/register", data=user_info)  
  
print(r.status_code)  # 打印请求返回的状态码

9session与cookie

#!/usr/bin/env python3  

from flask import Flask
from flask import url_for
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import make_response

# 初始化  
app = Flask(__name__)  

app.secret_key='kdjklfjkd87384hjdhjh'
  
# 设置多个路由  
@app.route('/')  
def index():  
    return 'Hello World!'  
  
@app.route('/a')  
def add():  
    return '1+1=2'  
  
#@app.route('/user/<username>')  
#def user_index(username):  
    # 在函数中指明变量名称username,就能获取到通过路由传入的变量username  
    #return render_template('user_index.html', username=username)  
  
@app.route('/user/<password>')  
def user_password(password):  
    print('User-Agent:', request.headers.get('User-Agent'))  
    print('time:', request.args.get('time'))  
    print('q:', request.args.get('q'))  
    print('issinge:', request.args.get('issinge'))  
    return 'password is {}'.format(password)  
  
@app.route('/post/<int:post_id>')  
def show_post(post_id):  
    return 'Post {}'.format(post_id)  
  
@app.route('/test')  
def test():  
    print(url_for('index'))  
    print(url_for('user_index', username='scj'))  
    print(url_for('show_post', post_id=1))  
    return 'test'  
  
@app.route('/<username>')  
def hello(username):  
    if username == 'handsomescj':  
        return 'Hello {}'.format(username)  
    else:  
        return redirect(url_for('index'))  
  
@app.route('/register', methods=['GET', 'POST'])  
def register():  
    print('method:', request.method)  
    print('name:', request.form['name'])  
    print('password:', request.form.get('password'))  
    print('hobbies:', request.form.getlist('hobbies'))  
    print('age:', request.form.get('age', default=18))  
    return 'register success!'  
    
@app.route('/set_session')  
def set_session():  
    # 设置session的持久化  
    session.permanent = True  
    session['username'] = 'scj' 
    return '成功设置session'  
  
@app.route('/get_session')  
def get_session():  
    value = session.get('username')    
    return '成功获取session值为:{}'.format(value)
    
@app.route('/set_cookie/<username>')  
def set_cookie(username):  
    resp = make_response(render_template('user_index.html', username=username))  
    resp.set_cookie('user', username)  # 使用'user'作为cookie的名字  
    return resp  
  
@app.route('/get_cookie')  
def get_cookie():  
    username = request.cookies.get('username')  # 使用'user'来检索cookie的值  
        return 'Hello {}'.format(username)  # 修正格式化字符串的语法  
    
  
if __name__ == '__main__':  
    app.run(debug=True)

10 errot404

#!/usr/bin/env python3  

from flask import Flask
from flask import url_for
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import make_response


# 初始化  
app = Flask(__name__)  

app.secret_key='kdjklfjkd87384hjdhjh'
  
# 设置多个路由  
@app.route('/')  
def index():  
    return 'Hello World!'  
  
@app.route('/a')  
def add():  
    return '1+1=2'  
  
@app.route('/user/<username>')  
def user_index(username):  
   if username == 'invalid'
   		abort(404)
   	return render_template('user_index.html',username=username)
  
@app.route('/user/<password>')  
def user_password(password):  
    print('User-Agent:', request.headers.get('User-Agent'))  
    print('time:', request.args.get('time'))  
    print('q:', request.args.get('q'))  
    print('issinge:', request.args.get('issinge'))  
    return 'password is {}'.format(password)  
  
@app.route('/post/<int:post_id>')  
def show_post(post_id):  
    return 'Post {}'.format(post_id)  
  
@app.route('/test')  
def test():  
    print(url_for('index'))  
    print(url_for('user_index', username='scj'))  
    print(url_for('show_post', post_id=1))  
    return 'test'  
  
#@app.route('/<username>')  
#def hello(username):  
#    if username == 'handsomescj':  
#        return 'Hello {}'.format(username)  
 #   else:  
#        return redirect(url_for('index'))  
  
@app.route('/register', methods=['GET', 'POST'])  
def register():  
    print('method:', request.method)  
    print('name:', request.form['name'])  
    print('password:', request.form.get('password'))  
    print('hobbies:', request.form.getlist('hobbies'))  
    print('age:', request.form.get('age', default=18))  
    return 'register success!'  
    
@app.route('/set_session')  
def set_session():  
    # 设置session的持久化  
    session.permanent = True  
    session['username'] = 'scj' 
    return '成功设置session'  
  
@app.route('/get_session')  
def get_session():  
    value = session.get('username')    
    return '成功获取session值为:{}'.format(value)
    
@app.route('/set_cookie/<username>')  
def set_cookie(username):  
    resp = make_response(render_template('user_index.html', username=username))  
    resp.set_cookie('user', username)  # 使用'user'作为cookie的名字  
    return resp  
  
@app.route('/get_cookie')  
def get_cookie():  
    username = request.cookies.get('username')  # 使用'user'来检索cookie的值  
        return 'Hello {}'.format(username)  # 修正格式化字符串的语法  
        
@app.route(404)
def not_found(error):
	return render_template('404.html'),404
    
  
if __name__ == '__main__':  
    app.run(debug=True)

404.html

错了,sb