首页 > 其他分享 >flask基本使用

flask基本使用

时间:2024-04-13 14:13:00浏览次数:27  
标签:基本 __ return name index flask app user 使用

 

flask是基于python开发并且依赖jinja2模版和werkzeug WSGI服务的一个微型框架(django使用的前端是自己的DTL)

 

安装flask

pip install flask

 

 

使用例一:

走的是http协议,新建一个py文件:

from flask import Flask

app=Flask(__name__)

@app.route('/')  #配路由的,先去执行了函数的返回结果放在这里
def index():
    return 'hello world'

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

 

 

 

 

 

例二:

from flask import Flask,request


app=Flask(__name__)

@app.route('/')   # 装饰器加括号和不加括号的区别
def index():
    # 当前请求地址,当前请求携带过来的数据
    print(request.path)
    return 'hello world'

@app.route('/hello')
def hello():

    print(request.path)
    return 'hello hellohello'
if __name__ == '__main__':
    app.run()
    # 请求来了,会执行 app(request),会触发谁?触发__call__方法

 

 

例三:三板斧(使用返回字符串、重定向、返回页面)

flask中返回字符串直接return '中间写字符串即可'

-return 字符串
-return render_template('index.html')
-return redirect('/login')

 

 

from flask import Flask,request,render_template,redirect

app=Flask(__name__)

@app.route('/')
def index():

    # return render_template('index.html')
    # return redirect('http://www.baidu.com')
    return redirect('hello')


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

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

 

 

 

登录,显示用户信息-小案例

路由写法(路径,支持的请求方式,别名)

@app.route('/login',methods=['GET','POST'],endpoint='l1')

 

 

模板语言渲染
-同dtl,但是比dtl强大,支持加括号执行,字典支持中括号取值和get取值


 分组(django中的有名分组)

 @app.route('/detail/<int:nid>',methods=['GET'])
    def detail(nid):

 

反向解析

-url_for('别名')

 

 

获取前端传递过来的数据

# get 请求
        request.query_string
      # post请求
      user = request.form.get('user')
      pwd = request.form.get('pwd')

 

main.py

from flask import Flask,render_template,request,redirect,session,url_for
app = Flask(__name__)
app.debug = True
app.secret_key = 'sdfsdfsdfsdf'

USERS = {
    1:{'name':'张三','age':18,'gender':'男','text':"道路千万条"},
    2:{'name':'李四','age':28,'gender':'男','text':"安全第一条"},
    3:{'name':'王五','age':18,'gender':'女','text':"行车不规范"},
}

@app.route('/detail/<int:nid>',methods=['GET'])
def detail(nid):
    user = session.get('user_info')
    if not user:
        return redirect('/login')

    info = USERS.get(nid)
    return render_template('detail.html',info=info)


@app.route('/index',methods=['GET'])
def index():
    user = session.get('user_info')
    if not user:
        # return redirect('/login')
        url = url_for('l1')
        return redirect(url)
    return render_template('index.html',user_dict=USERS)


@app.route('/login',methods=['GET','POST'],endpoint='l1')
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        # request.query_string
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        if user == 'zs' and pwd == '123':
            session['user_info'] = user
            return redirect('http://www.baidu.com')
        return render_template('login.html',error='用户名或密码错误')

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

 

 

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户列表</h1>
    <table>
        {% for k,v in user_dict.items() %}
        <tr>
            <td>{{k}}</td>
            <td>{{v.name}}</td>
            <td>{{v['name']}}</td>
            <td>{{v.get('name')}}</td>
            <td><a href="/detail/{{k}}">查看详细</a></td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>

 

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户列表</h1>
    <table>
        {% for k,v in user_dict.items() %}
        <tr>
            <td>{{k}}</td>
            <td>{{v.name}}</td>
            <td>{{v['name']}}</td>
            <td>{{v.get('name')}}</td>
            <td><a href="/detail/{{k}}">查看详细</a></td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>

 

 

login.html

Copy<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户登录</h1>
    <form method="post">
        <input type="text" name="user">
        <input type="text" name="pwd">
        <input type="submit" value="登录">{{error}}
    </form>
</body>
</html>

 

 

 

配置文件

我们这里指距离常用的三种方式

方式一

app.config['DEBUG'] = True
PS: 由于Config对象本质上是字典,所以还可以使用        app.config.update(...)

 

方式二

#通过py文件配置
app.config.from_pyfile("python文件名称")  #另开一个文件例如名字叫setting
如:
settings.py
DEBUG = True

 

方式三

app.config.from_object('settings.TestingConfig')

class Config(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI = 'sqlite://:memory:'


class ProductionConfig(Config):
    DATABASE_URI = 'mysql://user@localhost/foo'


class DevelopmentConfig(Config):
    DEBUG = True


class TestingConfig(Config):
    TESTING = True

 

 

路由系统

基本使用

@app.route('/detail/<int:nid>',methods=['GET'],endpoint='detail')

 

转换器

DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}

 

 

 

 

路由的本质

本质就是:app.add_url_rule()
endpoint:如果不写默认是函数名,endpoint不能重名

 

 

app.add_url_rule参数

@app.route和app.add_url_rule参数:
rule, URL规则
view_func, 视图函数名称
defaults = None, 默认值, 当URL中无参数,函数需要参数时,使用defaults = {'k': 'v'}
为函数提供参数
endpoint = None, 名称,用于反向生成URL,即: url_for('名称')
methods = None, 允许的请求方式,如:["GET", "POST"]
#对URL最后的 / 符号是否严格要求,默认严格,False,就是不严格
strict_slashes = None
    '''
        @app.route('/index', strict_slashes=False)
        #访问http://www.xx.com/index/ 或http://www.xx.com/index均可
        @app.route('/index', strict_slashes=True)
        #仅访问http://www.xx.com/index
    '''
#重定向到指定地址
redirect_to = None, 
    '''
        @app.route('/index/<int:nid>', redirect_to='/home/<nid>')
    '''

 

 

CBV

from flask import Flask,request,render_template,redirect
from flask import views

app=Flask(__name__)


# class IndexView(views.View):
#     methods = ['GET']
#     # decorators = [auth, ]
#     def dispatch_request(self):
#         print('Index')
#         return 'Index!'

def auth(func):
    def inner(*args, **kwargs):
        print('before')
        result = func(*args, **kwargs)
        print('after')
        return result

    return inner
class IndexView(views.MethodView):
    methods = ['GET']  # 指定运行的请求方法
    # 登录认证装饰器加在哪?
    decorators = [auth, ]  #加多个就是从上往下的效果
    def get(self):
        print('xxxxx')
        return "我是get请求"
    def post(self):
       return '我是post请求'

# 路由如何注册?
# IndexView.as_view('index'),必须传name
app.add_url_rule('/index',view_func=IndexView.as_view('index'))

if __name__ == '__main__':
    app.run()
    
    
# 用的比较少
# 继承views.MethodView,只需要写get,post,delete方法
# 如果加装饰器decorators = [auth, ]
# 允许的请求方法methods = ['GET'] 

 

标签:基本,__,return,name,index,flask,app,user,使用
From: https://www.cnblogs.com/97zs/p/18132790

相关文章

  • 在 Windows10 中使用 WSL2
    安装必备的功能使用win+i打开设置,依次点击应用→应用与功能→程序和功能→启用或关闭Windows功能勾选适用于Linux的Windows子系统与虚拟机平台确定并且重启配置组合键win+r输入powershell打开PowerShell窗口执行下面的命令设置为wsl2wsl--set-def......
  • SpringBoot中的Jetty使用及分析
    前言和Tomcat类似,Jetty也是一个Web应用服务器,相对于Tomcat,Jetty更加轻量、更加简易、更加灵活。今天通过代码来简单分析下SpringBoot中是如何启动Jetty的。Jetty简介使用importjava.io.File;importjava.io.IOException;importjava.net.InetAddress;import......
  • Go语言的100个错误使用场景(61-68)|并发实践
    目录前言9.并发实践9.1context的不恰当传播(#61)9.2开启一个协程但不知道何时关闭(#62)9.3在循环中没有谨慎使用协程(#63)9.4使用select和channel期待某个确定的行为(#64)9.5不使用用于通知的channel(#65)9.6不使用nilchannel(#66)9.7对channel的大小感到疑惑(#67)9.8忽视st......
  • 03_NET6中使用Autofac
    安装包:AutofacAutofac.Extensions.DependencyInjectionAutofac.Extras.DynamicProxy中文文档:欢迎来到Autofac中文文档!—Autofac4.0documentation(autofac-.readthedocs.io) 1.新建一个webapi项目新建一个AutofacMamager类,用于注册publicclassAutofacMamager......
  • SpringBoot使用 nacos 会默认加载项目名配置文件
    问题描述boostrap.yml配置如下spring:application:name:cnblogscloud:nacos:config:server-addr:http://ip:8848namespace:d8b0df04-aa58-4a5b-b582-7d133b9e8b2c#命名空间IDfile-extension:yamlusern......
  • Windows 软件管理工具 Scoop 的使用
    Windows软件管理工具Scoop的使用卸载Scoop打开PowerShell输入scoopuninstallscoop输入scooplist查看是否卸载成功安装Scoop打开PowerShell查看PowerShell版本Get-Host|Select-ObjectVersion确保安装PowerShell5(或更高版本,包括PowerShell核......
  • 02_Web Api使用Jwt
    JWT(JSONWebToken)是一种用于在网络应用之间传递信息的开放标准(RFC7519)。它使用JSON对象在安全可靠的方式下传递信息,通常用于身份验证和信息交换。在WebAPI中,JWT通常用于对用户进行身份验证和授权。当用户登录成功后,服务器会生成一个Token并返回给客户端,客户端在接下来的请求......
  • SeleniumBase 制作WEB用户使用导览,并导出 JS-使用笔记(三)
    自动化福音(爬虫、办公、测试等)SeleniumBase使用笔记(三)SeleniumBase制作WEB用户使用导览,并导出JSSeleniumBase包含强大的JS代码生成器,用于将Python转换为JavaScript,而制作用户导览,就是其中的应用之一,用户导览能将SaaS产品采用率提高10倍或更多目录创建导览......
  • Linux无管理员权限,使用conda安装jupyter的R语言环境
    解决了2天,坑点满满,哭死......
  • flask之ssti模版注入从零到入门
    前言在学习ssti模版注入的时候,发现国内文章对于都是基于python基础之上的,对于基础代码讲的较少,而对于一些从事安全的新手师傅们,可能python只停留在写脚本上,所以上手的时候可能有点难度,毕竟不是搞pythonflask开发。就本人学习ssti而言,入手有点难度,所以特写此文,对于一些不需要深......