一.Flask中的CBV

from flask import Flask, render_template
from flask import views
app = Flask(__name__, template_folder='temp')  # type:Flask
app.config['DEBUG'] = True
 
 
class LoginView(views.MethodView):   
 
    def get(self):
        return render_template('login.html')
 
    def post(self):
        return '登录成功'
 
 
app.add_url_rule('/login', endpoint=None, view_func=LoginView.as_view('login'))
# 路由地址   指定endpoint为none   as_view中的login为endpoint  
 
if __name__ == '__main__':
    app.run()
 

二. Flask 中的闪现(flash)

from flask import flash
flash('666', 'hu')
get_flashed_messages('hu')   # 结果[('hu','666')]
get_flashed_messages(category_filter='hu')
flash('666')
get_flashed_messages()        # 结果['666']

三. Flask-Session

 
    from flask_session import Session
    from flask import session
    
    app.config["SESSION_TYPE"] = "redis"
    app.config["SESSION_REDIS"] = Redis("127.0.0.1",6379,db=7)
    Session(app)
    
    session["user"] = "123"
    session.get("user")
flask中的session存放在浏览器中的cookie中

四.Flask中的WTForms

 
class ResForm(Form):
    username = simple.StringField(
        label='用户名',
        validators=[
            validators.DataRequired(message='用户名不能为空'),
            validators.Length(min=4, message='用户名不能低于五位数')
        ]
    )
    password =  simple.PasswordField(
        label='密码',
        validators=[
            validators.DataRequired(message='密码不能为空'),
            validators.Length(min=4,message='密码不能低于五位数')
        ]
    )
    re_password =  simple.PasswordField(
        label='确认密码',
        validators=[
            validators.DataRequired(message='密码不能为空'),
            validators.Length(min=4,message='密码不能低于五位数'),
            validators.EqualTo('password', message='密码不一致')
        ]
    )
    email = simple.StringField( label='邮箱',
        validators=[
            validators.Email(message='格式不正确'),
        ])
    sex = core.SelectField(
        label='性别',
        coerce=int,
        choices=((1, '男'),
                 (2, '女')
                 ),
        default=1
    )
    hobby = core.SelectMultipleField(
        label='爱好',
        coerce=int,
        choices=((1, '小萝莉'),
                 (2, '御姐'),
                 (3, '淑女'),
                 (4, '熟女'),
                 ),
        default=(1, 2 )
    )
 

五.DBUtils 数据库连接池

 
from DBUtils.PooledDB import PooledDB
import pymysql
 
class MySQLhelper(object):
    def __init__(self, host, port, dbuser, password, database):
        self.pool = PooledDB(
            creator=pymysql,  # 使用链接数据库的模块
            maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
            mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
            maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
            maxshared=3,
            # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
            blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
            maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
            setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
            ping=0,
            # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
            host=host,
            port=int(port),
            user=dbuser,
            password=password,
            database=database,
            charset='utf8'
        )
 
    def create_conn_cursor(self):
        conn = self.pool.connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        return conn,cursor
 
    def fetch_all(self, sql, args):
        conn,cursor = self.create_conn_cursor()
        cursor.execute(sql,args)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result
 
    def insert_one(self,sql,args):
        conn,cursor = self.create_conn_cursor()
        res = cursor.execute(sql,args)
conn.commit()
        conn.close()
        return res
 
    def update(self,sql,args):
        conn,cursor = self.create_conn_cursor()
        res = cursor.execute(sql,args)
conn.commit()
        print(res)
        conn.close()
        return res
 
 
sqlhelper = MySQLhelper("127.0.0.1", 3306, "root", "", "db7")
 
# res = sqlhelper.fetch_all("select * from userinfo where id=%s",(5,))
# print(res)
 
# res = sqlhelper.insert_one("insert into userinfo VALUES (%s,%s,%s)",(7,"jinwangba","66666"))
# print(res)
 
# sqlhelper.update("update user SET name=%s WHERE  id=%s",("yinwangba",1))

六.Flask请求上下文流程

 

flask的简单使用的更多相关文章

  1. Flask的简单认识

    Flask的简单认识 Flask是轻量级的框架,适用于简单的程序 与Django的比较: Django: 无socket,中间件,路由,视图(CBV,FBV),模板,ORM, cookie,sessi ...

  2. 使用Flask开发简单接口

    作为测试人员,在工作或者学习的过程中,有时会没有可以调用的现成的接口,导致我们的代码没法调试跑通的情况. 这时,我们使用python中的web框架Flask就可以很方便的编写简单的接口,用于调用或调试 ...

  3. Python: Flask框架简单介绍

    接触Python之后我第一次听说Flask,我就根据自己搜罗的知识尽可能简洁的说出来.如果不准确的地方还请指正,谢谢. Flask是什么?             Flask是基于Python编写的微 ...

  4. Flask实现简单的群聊和单聊

    Flask是使用python写的一个简单轻量级的框架,今天我们使用Flask实现一个简单的单聊和群聊功能 . 主要思路 : 前端登录聊天室,聊天室信息包含用户的登录信息,相当于一个登录功能,会把这个信 ...

  5. flask 完成简单查询请求处理,及跨域

    文章大纲 flask通用项目结构 flask 简介 主体代码逻辑 flask 跨域问题的处理 flask 日志 flask 微服务Flask-RESTful 启动服务命令 flask通用项目结构 | ...

  6. 使用Flask开发简单接口(1)--GET请求接口

    前言 很多想学习接口测试的同学,可能在最开始的时候,常常会因没有可以练习的项目而苦恼,毕竟网上可以练习的接口项目不多,有些可能太简单了,有些可能又太复杂了,或者是网上一些免费接口请求次数有限制,最终导 ...

  7. 使用Flask开发简单接口(2)--POST请求接口

    今天我们继续学习如何使用Flask开发POST接口:用户注册接口和用户登录接口. request接收参数 当我们在页面发出一个POST请求,请求传到服务器时,需要如何拿到当前请求的数据呢?在Flask ...

  8. 使用Flask开发简单接口(3)--引入MySQL

    前言 前面的两篇文章中,我们已经学习了通过Flask开发GET和POST请求接口,但一直没有实现操作数据库,那么我们今天的目的,就是学习如何将MySQL数据库运用到当前的接口项目中. 本人环境:Pyt ...

  9. 利用flask 实现简单模版站

    from flask import Flask,render_template from flask import request app = Flask(__name__) @app.route(' ...

随机推荐

  1. python列表的切片操作允许索引超出范围

    其余的不说,列表切片操作允许索引超出范围:

  2. x264_param_default分析

    {     /* 开辟内存空间*/     memset( param, 0, sizeof( x264_param_t ) );              /* CPU自动检测 */     par ...

  3. 【sql基础】按照名字分组查询时间最早的一条记录

    给出2种解决方案 rownumber SELECT * FROM ( SELECT IdentityID, OpenID, ROW_NUMBER() OVER(PARTITION BY OpenID ...

  4. 三、Sql Server 基础培训《进度3-是否使用外键(知识点学习)》

    学习作业3: 问题1:你觉得外键有哪些适用情况?哪些不适用情况?   问题2:本次实战案例,由你来架构,你觉得有必要建立外键吗? 说明你的理由?     ======================= ...

  5. 机器人学 —— 机器人感知(Location)

    终于完成了Robotic SLAM 所有的内容了.说实话,课程的内容比较一般,但是作业还是挺有挑战性的.最后一章的内容是 Location. Location 是 Mapping 的逆过程.在给定ma ...

  6. 禅道迁移(windows_to_linux)

    需求分析 随着禅道数据的增加,原来通过虚拟机提供的mysql服务器相应速度跟不上需求.且原来禅道的前端与数据库分离安装在windows与linux中,现在提供实体服务器,需要将禅道环境迁移. 确认环境 ...

  7. 联想R720面板右下部分按压后和上面按键串联了

    如图所示的位置,一用力按压,就会触发键盘的按键. 前提: 本人刚刚加装了内存条,内存条是京东买的 十铨(Team) DDR4 2400 8GB 笔记本内存,安装完内存以后,发现电脑出了这样的问题. 解 ...

  8. maven 私服同步无法获取依赖的pom.xml的依赖

    项目中引入了依赖: <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hado ...

  9. SVN版本管理系统的使用(CentOS+Subversion+Apache+Jsvnadmin+TortoiseSVN)

    1.服务器: 192.168.4.221root 用 户操作安装 装 apache# yum install httpd httpd-devel# service httpd start# chkco ...

  10. Moving Tables---(贪心)

    Problem Description The famous ACM (Advanced Computer Maker) Company has rented a floor of a buildin ...