[flask]基础知识

2023-05-16

Flask 基础知识

基本框架结构

from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem

app = Flask(__name__)

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


@app.route('/')
@app.route('/hello')
def HelloWorld():
    restaurant = session.query(Restaurant).first()
    items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)
    output = ''
    for i in items:
        output += i.name
        output += '</br>'
        output += i.price
        output += '</br>'
        output += i.description
        output += '</br>'
        output += '</br>'
    return output

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

路由 route

Flask Documentation on Routing :
http://flask.pocoo.org/docs/0.10/quickstart/#routing
flask路由的格式为/path/<type:value>/path
其中,type可以为string, int, path

模板 template

HTML Character Escaping is a way of writing special characters inside of HTML code, this is a different concept from the HTML escaping with python code
注意模板文件都应该放入名为templates的文件夹。

URL-Buiding : url_for

url_for 用来将模板里的超链接转化为flask定义的后端接口函数。例如:
./templates/menu.html

<h1>{{restaurant.name}}</h1>

{% for i in items %}
<br>
<h2>{{i.name}}</h2>
{{i.description}}
<br>
{{i.price}}
<a href={{url_for('edit_menu_item', restaurant_id=restaurant.id, menu_id=i.id)}}>Edit</a>
<a href={{url_for('delete_menu_item', restaurant_id=restaurant.id, menu_id=i.id)}}>Delete</a>
<br>
<br>
{% endfor %}

./flask_server.py

import flask
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem

app = Flask(__name__)

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


@app.route('/')
@app.route('/hello')
def HelloWorld():
    restaurant = session.query(Restaurant).first()
    items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)
    output = ''
    for i in items:
        output += i.name
        output += '</br>'
        output += i.price
        output += '</br>'
        output += i.description
        output += '</br>'
        output += '</br>'
    return output

@app.route("/restaurant/<int:restaurant_id>/new")
def new_menu_item(restaurant_id):
    return "create new menu item for the Restaurant(id={})".format(restaurant_id)

@app.route("/restaurant/<int:restaurant_id>/edit/<int:menu_id>")
def edit_menu_item(restaurant_id, menu_id):
    return "edit the Menu(id={}) in Restaurant(id={})".format(menu_id, restaurant_id)

@app.route("/restaurant/<int:restaurant_id>/delete/<int:menu_id>")
def delete_menu_item(restaurant_id, menu_id):
    return "delete the Menu(id={}) in Restaurant(id={})".format(menu_id, restaurant_id)

@app.route("/restaurant/<int:restaurant_id>/menus")
def menus(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).first()
    
    if restaurant:
        menus = session.query(MenuItem).filter_by(restaurant_id=restaurant_id).all()
        return flask.render_template('menu.html', items=menus, restaurant=restaurant)
    return "you come to a wrong page!"

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8080)

Form Requests and Redirects 表单提交和跳转

常用的三个函数

from flask import url_for, redirect, request

url_for 用于与响应函数绑定
redirect用于重定向
request用于获取form表单中的值


import flask
from flask import Flask, url_for, redirect, request
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem

app = Flask(__name__)

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


@app.route('/')
@app.route('/hello')
def HelloWorld():
    restaurant = session.query(Restaurant).first()
    items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)
    output = ''
    for i in items:
        output += i.name
        output += '</br>'
        output += i.price
        output += '</br>'
        output += i.description
        output += '</br>'
        output += '</br>'
    return output

@app.route("/restaurant/<int:restaurant_id>/new")
def new_menu_item(restaurant_id):
    return "create new menu item for the Restaurant(id={})".format(restaurant_id)

@app.route("/restaurant/<int:restaurant_id>/edit/<int:menu_id>", methods=['GET', 'POST'])
def edit_menu_item(restaurant_id, menu_id):
    menu = session.query(MenuItem).filter_by(id=menu_id).first()

    if request.method == 'POST':
        if request.form['name']:
            menu.name = request.form['name']
            session.add(menu)
            session.commit()
        return redirect(url_for('menus', restaurant_id=restaurant_id))
    else:
        return flask.render_template('editmenu.html', item=menu)

@app.route("/restaurant/<int:restaurant_id>/delete/<int:menu_id>")
def delete_menu_item(restaurant_id, menu_id):
    return "delete the Menu(id={}) in Restaurant(id={})".format(menu_id, restaurant_id)

@app.route("/restaurant/<int:restaurant_id>/menus")
def menus(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).first()
    
    if restaurant:
        menus = session.query(MenuItem).filter_by(restaurant_id=restaurant_id).all()
        return flask.render_template('menu.html', items=menus, restaurant=restaurant)
    return "you come to a wrong page!"

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8080)

message flashing

message flashing 用于与用户进行交互,反映用户操作产生的结果。

from flask import flash

app.secret_key = ‘super_secret_key’ 用来创建用户相关的会话(session)事务
在这里插入图片描述

在这里插入图片描述


from crypt import methods
import flask
from flask import Flask, url_for, redirect, request, flash
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem

app = Flask(__name__)

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


@app.route('/')
@app.route('/hello')
def HelloWorld():
    restaurant = session.query(Restaurant).first()
    items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)
    output = ''
    for i in items:
        output += i.name
        output += '</br>'
        output += i.price
        output += '</br>'
        output += i.description
        output += '</br>'
        output += '</br>'
    return output

@app.route("/restaurant/<int:restaurant_id>/new", methods=['GET', 'POST'])
def new_menu_item(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).first()
    if restaurant:
        if request.method == 'GET':
            return flask.render_template('createmenuitem.html', restaurant=restaurant)
        
        else:
            menu_item_name = request.form['name']
            if menu_item_name:
                session.add(MenuItem(name=menu_item_name, restaurant_id=restaurant_id))
                session.commit()
                flash("successfully created a new Menu Item!")
            return redirect(url_for('menus', restaurant_id=restaurant_id))
    return "you come to a wrong page"

@app.route("/restaurant/<int:restaurant_id>/edit/<int:menu_id>", methods=['GET', 'POST'])
def edit_menu_item(restaurant_id, menu_id):
    menu = session.query(MenuItem).filter_by(id=menu_id).first()

    if request.method == 'POST':
        if request.form['name']:
            menu.name = request.form['name']
            session.add(menu)
            session.commit()
            flash("one Menu item has been editted")
        return redirect(url_for('menus', restaurant_id=restaurant_id))
    else:
        return flask.render_template('editmenu.html', item=menu)

@app.route("/restaurant/<int:restaurant_id>/delete/<int:menu_id>", methods=['GET','POST'])
def delete_menu_item(restaurant_id, menu_id):
    menu = session.query(MenuItem).filter_by(id=menu_id).first()
    if menu:
        if request.method == 'POST':
            session.delete(menu)
            session.commit()
            flash("one menu item has been deleted")
        else:
            return flask.render_template('deletemenu.html', item=menu)
    return redirect(url_for('menus', restaurant_id=restaurant_id))

@app.route("/restaurant/<int:restaurant_id>/menus")
def menus(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).first()
    
    if restaurant:
        menus = session.query(MenuItem).filter_by(restaurant_id=restaurant_id).all()
        return flask.render_template('menu.html', items=menus, restaurant=restaurant)
    return "you come to a wrong page!"

if __name__ == '__main__':
    app.secret_key = 'super_secret_key' # flash 
    app.debug = True
    app.run(host='0.0.0.0', port=8080)

对象序列化便于传递数据

class MenuItem(Base):
    __tablename__ = 'menu_item'
    name =Column(String(80), nullable = False)
    id = Column(Integer, primary_key = True)
    description = Column(String(250))
    price = Column(String(8))
    course = Column(String(250))
    restaurant_id = Column(Integer,ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant) 

#We added this serialize function to be able to send JSON objects in a serializable format
    @property
    def serialize(self):
       return {
           'name'         : self.name,
           'description'  : self.description,
           'id'           : self.id,
           'price'        : self.price,
           'course'       : self.course,
       }
from flask import jsonify

上面的函数serialize将被jsonify调用进行对象序列化

@app.route('/restaurants/<int:restaurant_id>/menu/JSON')
def restaurantMenuJSON(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    items = session.query(MenuItem).filter_by(
        restaurant_id=restaurant_id).all()
    return jsonify(MenuItems=[i.serialize for i in items])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[flask]基础知识 的相关文章

  • 关于linux日志中存在大量martian source 日志信息的原因分析与理解

    在查看日常维护的一台Linux服务器的系统日志时 xff0c 发现有大量的类似如下的信息 xff1a Jan 17 00 33 34 test4 kernel 2170 725322 martian source 192 168 10 25
  • [C#] WinForm/WPF 实现数据库连接与操作(MySQL)

    目录 x1f33f 前言 x1f33f MySQL数据库简介 x1f33f 数据库的基本概念 x1f33f ADO NET体系结构 数据提供程序 NET Framework Data Provider 程序数据集 DataSet x1f33
  • 记录阿里技术面试全流程

    最近社招面试了阿里技术开发 xff0c 记录一下阿里技术面试时间流程 阿里招聘流程 xff0c 阿里审批流程 阿里入职流程 xff0c 阿里入职时间等说法 xff0c 以便给其他面试者一个时间参考 xff0c 毕竟等待的过程是痛苦的 第 1
  • 打造自己的Android源码学习环境之五:编译Android源代码

    打造自己的Android源码学习环境之五 xff1a 编译Android源代码 下载android源代码之后 xff0c 可以开始编译了 0 编译Android源码 0 1 设置环境 当前目录是执行repo init时所在的目录 span
  • stm32f10x.h 地址映射

    stm32f10x h 是stm32 的外设的地址映射 xff0c 把抽象的内存通过一个个宏 xff0c 映射 到了见名知义的程度 通过 typedef 兼容了st公司的3 0版的库 中的一些数据类型 span class hljs key
  • xrandr、arandr ubuntu 外接显示器,屏幕分辨率调整。

    简介 xrandr是RandR官方的配置工具 xff0c 一般用来在linux桌面中设置桌面分辨率 扩展屏幕等 arandr 是xrandr的GUI版本 xff0c 提供了用户可交互的界面版本 安装 xrandr GUI版本的linux系统
  • 最适合开发VR游戏大作的游戏引擎——Unity

    近两年来 xff0c 我们不断被承诺 VR 游戏时代的到来 xff0c 然而除了 Google CardBroad 这种可以拿硬纸板 DIY 的小玩意外并没有见过真正意义上的头显 直到去年年底游戏外设王者雷蛇推出了 VR 游戏头显后 xff
  • 没有在2016年当过前端程序员的设计师不是好产品经理

    我是一个脑洞大 笑点低 间歇性 有毛病 的理工科产品经理 xff0c 因为兴趣广泛 xff0c 在2016年越俎代庖承担了一些UI设计师和前端程序员该做的工作 程序员鼓励师 产品经理的故事 有的产品经理自以为能改变世界 xff0c 其实完全
  • 转身不带走一丝云彩--我的2014

    时间或许就是这样不管你愿意不愿意都会毫不犹疑的向前 xff0c 逼你成长 2014年得到了很多也失去了很多 xff0c 我对未来还是有诸多憧憬的 谨以此文献给过去的时光 xff0c 也希望对后来人能有所帮助 改变篇 相比于2013年 xff
  • 手机相机接口介绍

    原文来自公众号 xff1a 工程师看海 相机是手机中非常重要的模组之一 xff0c 已成为智能手机的标配 xff0c 其按布局可以分为前摄和后摄 xff0c 按功能可以分为自拍相机 主相机 超广角 长焦和微距等 不同功能的相机有不同功能的结
  • 添加控制文件(add control file)

    1 一致性关闭数据库 shutdown immediate 2 通过 spfile 创建 pfile create pfile from spfile 3 修改 pfile xff0c 增加一个控制文件 vi pfile 4 在操作系统上通
  • Linux CentOS 7 最详细的zimbra开源邮件服务器安装搭建

    1 环境 网络 xff1a 飞塔防火墙用于端口映射 系统 xff1a Centos7 ip地址 xff1a 10 10 104 130 xff08 这里用的是本地服务器 xff09 域名 xff1a mail zimbra com span
  • CentOS安装MySQL8详细步骤

    Centos安装Mysql8详细步骤 环境 xff1a CentOS7 43 Centos8 rpm包安装 一 下载mysql rpm bundle包 复制下载连接下载 span class token function wget span
  • js清除浏览器缓存的几种方法

    一 CSS和JS为什么带参数 xff08 形如 css t 61 与 js t 61 xff09 怎样获取代码 css和js带参数 xff08 形如 css t 61 与 js t 61 xff09 使用参数有两种可能 xff1a 第一 脚
  • ubuntu14.04安装python scipy

    参考文章ubuntu下安装python scipy 安装出现的问题和文章中一模一样 xff0c 并且按文章中的解决办法得到了解决
  • 「Debian/Ubuntu」- 常用仓库(源)整理 @20210318

    Debian Debian Stable deb https mirrors aliyun com debian stable main contrib non free deb https mirrors aliyun com debia
  • 物流定位系统项目qt代码

    头文件 ifndef USER INTERFACE H define USER INTERFACE H include lt QWidget gt include lt QLabel gt include lt QMouseEvent gt
  • Django中ImageField的使用

    from django db import models from django contrib import admin Create your models here class AdminUser models Model login
  • 四旋翼无人机原理以及组装过程

    1 硬件组成 xff1a 机架 xff0c 4个螺旋桨 xff0c 4个电机 xff0c 4个电调 xff0c 1信号接收器 xff0c 1个飞控板 xff0c 1个 稳压模块 xff0c 一个电池 螺旋桨 xff1a 四个螺旋桨都要提供升
  • 2021-09-08

    工业相机精度调研 本文主要总结工业相机中面阵和线阵相机的精度调研 面阵相机 xff1a 检测场景 xff1a 常用的高精度为3 45微米相元相机 xff0c 常规可搭配0 5 xff0c 1 xff0c 2 xff0c 4倍远心镜头 在4倍

随机推荐

  • 22年新款MacBookAir屏幕解析

    先说结论 xff1a 搭载M2芯片的AIR xff0c 很值得买 屏幕 xff1a Liquid视网膜显示屏 像素 xff1a 2550 1664 亮度 xff1a 500nit 色域 xff1a P3 技术 xff1a 原彩显示技术 Li
  • 不确定需求条件下的供应链决策分析 (zt)

    xff11 供应链与不确定性 xff11 xff0e xff11 供应链关系的特征 供应链关系不应简单理解为是由产品制造上的相关关系 xff08 即从原材料到半成品再到最终产品的转换过程 xff09 而形成的企业之间的相关关系 xff0c
  • Halcon无图像旋转时的图像拼接

    为了将尺寸较大的产品拍完 xff0c 可采用分区拍摄再拼图的方式 那么 xff0c 如何使用Halcon中的算子进行图像拼接呢 xff1f 本文介绍一种在相机无旋转的情况下使用tile images offset进行图像拼接的方法 该方法计
  • Halcon中count_obj算子及其异常分析

    count obj算子 count obj算子是用来计算输入区域中连通域的个数 更直观的说法是 xff0c 计算Region中有几个单独的区域 一般用在connection算子之后 xff0c 该算子的作用是将输入区域分割成单独的连通域 异
  • Halcon中 reduce_domain算子和crop_domain算子的使用及配合

    1 reduce domain算子 reduce domain span class hljs keyword Image span Region ImageReduced 其中 xff0c span class hljs keyword
  • 卷帘曝光和全局曝光的差别

    全局曝光和卷帘曝光是常见的相机曝光方式 一般来说 xff0c CCD相机是全局曝光 xff0c 而CMOS相机则存在卷帘曝光 那么 xff0c 这两种方式孰优孰劣呢 xff1f 或者说 xff0c 他们两者的差别在哪里呢 xff1f 那么
  • 自动化设备的软件框架

    自动化设备的软件主要由2部分组成 xff1a 1是运动控制部分的软件实现 xff0c 2是上位机处理数据并显示结果的软件实现 运动控制的实现 第1部分的实现主要有2种方式 xff0c 一种是用板卡控制的方式 xff0c 一种是用PLC控制的
  • Halcon中两种实现旋转的方法rotate_image和affine_trans_image

    Halcon中实现旋转的方式由两种 一种是rotate image xff0c 该方式实现简单 xff0c 但只能绕中心旋转 二是affine trans image xff0c 该方式实现较复杂 xff0c 但是可以实现绕任意位置的旋转
  • 一文搞定深度学习入门级电脑硬件配置

    对于刚接触深度学习的学友而言 xff0c 可能都会碰到电脑配置的问题 xff0c 比如显卡型号 内存容量 处理器型号等 好的电脑配置 xff0c 比如GPU加速的显卡 xff0c 是能够有效缩短算法的训练时间的 xff0c 这能让人尽快的看
  • 一文详解numpy中np.nonzero()函数

    np nonzero函数是numpy中用于得到数组array中非零元素的位置 xff08 数组索引 xff09 的函数 一般来说 xff0c 通过help xff08 np nonzero xff09 能够查看到该函数的解析与例程 但是 x
  • Matlab笔记:将列向量直接赋值给行向量

    在别人的matlab代码中看到 xff0c 将列向量赋值给行向量 最初还以为是别人的代码有bug xff0c 实际上运行后才发现是由自己的无知造成的 因此 xff0c 将如下一小段测试的代码贴出来 xff0c 向量的维度由左值 xff08
  • 使用已训练好的caffe模型的步骤

    如何使用生成的模型 xff0c 可能是在训练好模型之后 xff0c 需要考虑的问题 实际上 xff0c caffe是存在两种接口来进行调用模型 xff1a 1种是基于python的 xff0c 另一种则是基于c 43 43 的 我个人是倾向
  • 怎么开发爬虫软件?

    怎么开发爬虫软件 xff1f 来自 ITPUB博客 xff0c 链接 xff1a http blog itpub net 69941520 viewspace 2650981 xff0c 如需转载 xff0c 请注明出处 xff0c 否则将
  • 来聊聊ios下的url缓存问题

    一 关于同一个url的多次请求 有时候 xff0c 对同一个URL请求多次 xff0c 返回的数据可能都是一样的 xff0c 比如服务器上的某张图片 xff0c 无论下载多少次 xff0c 返回的数据都是一样的 01220830391450
  • openstack ovs-vswitch收包流程

    数据包从物理网卡进入虚拟机的流程 物理网卡处理 NIC 收到数据包 xff0c 会先将高低电信号转换到网卡 FIFO 存储器 NIC 首先申请 Ring buffer 的描述 xff0c 根据描述找到具体的物理地址 xff0c NIC 会使
  • 9个常用的Shell脚本

    1 Dos 攻击防范 xff08 自动屏蔽攻击 IP xff09 bin bash DATE 61 date 43 d b Y H M LOG FILE 61 usr local nginx logs demo2 access log AB
  • google breakpad /qbreakpad 在 arm移植

    google breakpad qbreakpad 在 arm移植 breakpad在arm linux上移植 xff0c 集成到qt中生成qbreakpad 参考文档 xff1a Google Breakpad 之一 xff0c 跨平台c
  • 无限递归(与无限循环一样)

    public int sumByMax int max if max lt 61 2 return max 43 sumByMax max 1 else return max
  • [leetcode] Maximum Split of Positive Even Integers

    Maximum Split of Positive Even Integers You are given an integer finalSum Split it into a sum of a maximum number of uni
  • [flask]基础知识

    Flask 基础知识 基本框架结构 span class token keyword from span flask span class token keyword import span Flask span class token k