当前位置: 首页 > 编程日记 > 正文

python框架之Flask基础篇(一)

一.第一个hello world程序

# coding=utf-8
from flask import Flaskapp = Flask(__name__)@app.route('/')
def hello_world():return 'Hello World!'if __name__ == '__main__':app.run(debug=True)

1.app参数的设置:

 以下几种方式全部拿debug模式举例:
.方式一:将参数设置到app.config字典中:

app.config["DEBUG"] = True

.方式二:加载文件:  
  1. 先在根目录下创建一个config.py文件,然后写入DEBUG = True 
  2. 然后在含有app文件中设置参数:

app.config.from_pyfile("config.py")

.方式三:加载对象(实际开发中一般用这个):  
  1. 先在根目录下创建一个config.py文件,然后写入如下代码:

class Config(object):DEBUG = True

  2. 在app文件中导入config文件中的Config类。  
  3. 然后设置:

app.config.from_object("Config")

.方式四:app的属性

app.debug = True

也可以

app.run(debug=True)

但是这种方式不同用,只是针对debug模式可以这样设置。

2.取app.config参数中的值:

1)app.config.get("DEBUG")

   2)current_app.config.get("DEBUG")

   3)Config.DEBUG

 

二.路由的各种定义方式

1.路由的查找方式:

2.flask中内置的路由转换器(路由传参的几种形式)

a.系统默认的类型default就是string类型,也就是说进行路由的参数匹配的时候,系统默认会将参数当作string类型进行匹配。下面举例说明:

 1 @app.route('/<str>')
 2 def print_str(str):
 3     print type(str)    # 结果为:<type 'unicode'>
 4     return str
 5 
 6 
 7 @app.route('/<string:str>')
 8 def print_str1(str):
 9     print type(str)    # 结果为:<type 'unicode'>
10   return str

 1 @app.route('/<any(hello,python,java,"javascript:;"):str>')
 2 def print_any(str):   # 只能匹配括号里面的数据,并且引号里面的数据可以随意写
 3     print type(str)
 4     return str
 5 
 6 
 7 @app.route('/<path:str>')     # http://localhost:5000/path/str
 8 def print_path(str):
 9     print type(str)
10     return str    # 结果为:path/str
11 
12 
13 @app.route('/<int:str>')    # 页面传过来的数据(字符串类型)在这里直接转换为int类型
14 def print_int(str):
15     print type(str)    # <type 'int'>
16     return str(str)     # 此时将数据返回给页面的时候必须转换为字符串类型
17 
18 @app.route('/<float:str>')  # 只有当页面传递过来的是小数float转换器才起作用
19 def print_float1(str):
20     print type(str)    # <type 'float'>
21     return str(str)

b.     uuid是32位16进制的数字。

3.路由的重定向

  1)重定向的方法是redirect()常常和url_for一起使用。比如:redirect(url_for(“视图函数的方法名”))

4.返回Json数据的两种方法:

  1)json.dumps("字典")

  2)jsonify("字典")

第一种方法仅仅是将字典转换为字符串返回给页面,响应头的Content-Type为text/html。

第二种方法是将字典转换为json返回给页面,响应头的Content-Type为application/json。这是开发中比较常用的方法。

现在的需求是用第一种方法还要达到第二种方法的效果,代码为:

return json.dumps(“字典”), 200, {'Content-Type': 'application/json'}

5.自定义正则路由转换器

1)导入包

from werkzeug.routing import BaseConverter

2)仿照BaseConverter自定义一个类

class RegexConverter(BaseConverter):def __init__(self,url_map,*args):super(RegexConverter,self).__init__(url_map)self.regex = args[0]

3)将自定义的类添加到路由转换器的字典中

app.url_map.converters["re"] = RegexConverter  # 这句话相当于将自己定义的类用re来表示

  4)将正则路由转换器应用到实例中

@app.route('/<re(r"\d{2}"):str>')  # 只能匹配两位数字  re(“正则”) ===>  相当于执行了RegexConverter中的init方法,将正则赋值给self.regex
def print_str(str):return str

转载于:https://www.cnblogs.com/RomanticLife/p/8362022.html

相关文章:

flask部署机器学习_如何开发端到端机器学习项目并使用Flask将其部署到Heroku

flask部署机器学习Theres one question I always get asked regarding Data Science:关于数据科学&#xff0c;我经常被问到一个问题&#xff1a; What is the best way to master Data Science? What will get me hired?掌握数据科学的最佳方法是什么&#xff1f; 什么会雇…

UVALive2678:Subsequence

UVALive2678:Subsequence 题目大意 给定一个数组A和一个整数S。求数组A中&#xff0c;连续且之和不小于S的连续子序列长度最小值。 要求复杂度:Ο(n) Solution 用变量L表示所选区间最左端下标&#xff0c;用变量R表示所选区间最右端下标&#xff0c;用变量sum表示所选区间的和。…

【BZOJ-3712】Fiolki LCA + 倍增 (idea题)

3712: [PA2014]Fiolki Time Limit: 30 Sec Memory Limit: 128 MBSubmit: 303 Solved: 67[Submit][Status][Discuss]Description 化学家吉丽想要配置一种神奇的药水来拯救世界。吉丽有n种不同的液体物质&#xff0c;和n个药瓶&#xff08;均从1到n编号&#xff09;。初始时&am…

访问系统相册或调用摄像头

头文件&#xff1a;#import <MobileCoreServices/MobileCoreServices.h> 协议&#xff1a;<UINavigationControllerDelegate, UIImagePickerControllerDelegate> // 调用系统相册获取图片 - (IBAction)getImageFromAlbum:(id)sender {// 判断系统相册是否可用&…

unity镜像_通过镜像学习Unity Multiplayer Basics

unity镜像Unity is one of the most well-known and established engines for game development, and Mirror is a third-party, open source networking solution that allows you to add multiplayer to your games.Unity是最著名的游戏开发引擎之一&#xff0c;而Mirror是第…

java内存模型和线程安全

转载于:https://www.cnblogs.com/Michael2397/p/8397451.html

测试,发布,质量保障,用户体验

1.在实际项目中何时开始设计用户体验&#xff1a;用户的第一印象&#xff1b;从用户的角度考虑问题&#xff1b;软件啊服务始终要记住用户的选择&#xff1b;短期刺激和长期影响 2.测试经验交流&#xff1a;基本名词解释及分类&#xff1b;按测试设计的方法分类&#xff1b;按测…

UIImage存为本地文件与UIImage转换为NSData

UIImage *image"XXX"; //png格式 NSData *imagedataUIImagePNGRepresentation(image); //JEPG格式 //NSData *imagedataUIImageJEPGRepresentation(image); NSArray*pathsNSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString …

如何在JavaScript中实现链接列表

If you are learning data structures, a linked list is one data structure you should know. If you do not really understand it or how it is implemented in JavaScript, this article is here to help you. 如果您正在学习数据结构&#xff0c;则链表是您应该知道的一种…

SVG.path_不连续的线段

1、之前 用<path/>画的 线段等 都是连续的&#xff0c;想知道 是否能画 不连续的线段等 结论&#xff1a;可以 2、测试代码&#xff1a; <?xml version"1.0" encoding"UTF-8"?> <svg width"1000" height"800" viewBo…

Leetcode 之Binary Tree Postorder Traversal(44)

后序遍历&#xff0c;比先序和中序都要复杂。访问一个结点前&#xff0c;需要先判断其右孩子是否被访问过。如果是&#xff0c;则可以访问该结点&#xff1b;否则&#xff0c;需要先处理右子树。 vector<int> postorderTraversal(TreeNode *root){vector<int> resu…

如何创建自己的ESLint配置包

ESLint is a powerful tool that helps you enforce consistent coding conventions and ensure quality in your JavaScript codebase. ESLint是一个功能强大的工具&#xff0c;可帮助您实施一致的编码约定并确保JavaScript代码库的质量。 Coding conventions are sometimes …

MySQL更新命令_UPDATE

创建测试表 mysql> CREATE TABLE product (-> proID int(11) NOT NULL AUTO_INCREMENT COMMENT 商品表主键,-> price decimal(10,2) NOT NULL COMMENT 商品价格,-> type int(11) NOT NULL COMMENT 商品类别(0生鲜,1食品,2生活),-> dtime datetime N…

KVC与KVO

1、键值编码KVC常用的KVC操作方法如下&#xff1a;• 动态设置&#xff1a; setValue:属性值 forKey:属性名&#xff08;用于简单路径&#xff09;、setValue:属性值 forKeyPath:属性路径&#xff08;用于复合路径&#xff0c;例如Person有一个Account类型的属性&#xff0c…

javaScript 工作必知(三) String .的方法从何而来?

String 我们知道javascript 包括&#xff1a;number&#xff0c;string&#xff0c;boolean,null,undefined 基本类型和Object 类型。 在我的认知中&#xff0c;方法属性应该是对象才可以具有的。 var str"hello,world";var sstr.subString(1,4);//ellalert(typeof…

s3 aws_您需要了解的有关AWS S3的所有信息

s3 awsThis article will provide an in-depth introduction to AWS S3 — the secure, scalable, and super cheap storage service from Amazon Web Services.本文将深入介绍AWS S3-来自Amazon Web Services的安全&#xff0c;可扩展和超便宜的存储服务。 If you have eve…

untitled与前端——初学

“前端” 啥&#xff1f; 百度百科&#xff1a; 就是制作一网页界面。比如360浏览器打开&#xff0c; 包括界面布局设计&#xff0c;搜索框&#xff0c;点击字或图标跳到另一个页面等。 软件Untitled 下载网址&#xff1a;http://www.jetbrains.com/ 下拉 点download&#xff0…

NSThread

NSThread是轻量级的多线程开发&#xff0c;使用起来也并不复杂&#xff0c;但是使用NSThread需要自己管理线程生命周期。 可以使用对象方法&#xff1a; (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument 直接将操作添加到线程中并…

异步发送邮件、短信、微信

用户创建订单的按钮点击后&#xff0c;服务器存储这个订单信息后&#xff0c;调用发送短信、邮件、微信的接口&#xff0c;发送消息。而发送短信、邮件、微信都要涉及第三方的处理&#xff0c;服务器又要发送一个新的包裹给一个新的服务器&#xff0c;告诉他帮我发一个信息出去…

英语面试简短问题_用简单的英语解释产品设计

英语面试简短问题Product design is the process you go through when you conceptualize and build a product.产品设计是概念化和构建产品时要经历的过程。 The path to building – hardware, software, or even simple prototypes – has different steps and approaches.…

6-12 二叉搜索树的操作集

6-12 二叉搜索树的操作集&#xff08;30 分&#xff09; 本题要求实现给定二叉搜索树的5种常用操作。 函数接口定义&#xff1a; BinTree Insert( BinTree BST, ElementType X ); BinTree Delete( BinTree BST, ElementType X ); Position Find( BinTree BST, ElementType X );…

iOS关于自定义rightBarButtonItem

在常见iOS开发中,我们常遇到这样的需求,如下: 我们需要自定义导航栏右侧按钮,常见的自定义包装按钮如下: //设置rightItem; UIButton *btn [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame CGRectMake(0, 0, 40, 30); btn.selected NO; [btn setTitle:"管理&…

URL里汉字转码

URL里面不能包含中文。 解决办法&#xff1a;进行转码 NSString *urlStr[NSString stringWithFormat:kLotteryBar_putOutReviewUrl,_token,self.reviews_id,_User_Id,reviews_content]; urlStr[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

electron.js_在使用Electron.js之前我希望知道的事情

electron.jsIn this article, Ill share how you can avoid some of the mistakes I made when learning about Electron.js &#x1f926;‍♂️. I hope it helps!在本文中&#xff0c;我将分享如何避免在学习Electron.js &#x1f926;‍&#x1f926;️时犯的一些错误。 希…

Entity Framework的启动速度优化

最近开发的服务放到IIS上寄宿之后&#xff0c;遇到一些现象&#xff0c;比如刚部署之后&#xff0c;第一次启动很慢&#xff1b;程序放置一会儿&#xff0c;再次请求也会比较慢。比如第一个问题&#xff0c;可以解释为初次请求某一个服务的时候&#xff0c;需要把程序集加载到内…

NSURLConnection的简单使用

遵循代理&#xff1a;NSURLConnectionDataDelegate -(void)fetchWebData:(id)sender{ self.isLoadingYES;NSString *urlStrkRequestUrlStr(self.page);NSURL *url[NSURL URLWithString:urlStr];NSURLRequest *request[NSURLRequest requestWithURL:url];self.connection[N…

tcp reno_如何使用称为Reno Expo的简单入门工具包构建全栈应用程序

tcp renoBuilding any new project from scratch can be intimidating. Theres a lot to decide before you can even start coding to test out your idea.从头开始构建任何新项目都可能令人生畏。 在开始编码以检验您的想法之前&#xff0c;还有很多决定。 How are you buil…

不同命名空间的对象二进制反序列化问题

本质上说&#xff0c;这并不是二进制序列化的问题&#xff0c;甚至不关序列化的问题。 你想要的是在两个内部结构一致但在不同命名空间&#xff08;甚至不同项目&#xff09;的同名类间做类型转换。 这个问题很常见&#xff0c;因为实际工作中经常会有此类需求&#xff0c;但是…

对大文件的断点续传

注&#xff1a;#import "YGFileDownloader.h"是对NSURLConnection的简单封装 #import "YGResumeDownloadViewController.h" #import "NSStringutil.h"#import "YGFileDownloader.h"#define URL "http://dlsw.baidu.com/sw-searc…

bootstrap modal 弹出效果

window.showMsg function (msg) {//显示悬浮窗$("#autoCloseModal").modal("show")//设置文本内容$("#autoCloseModal #autoCloseModalBody").html("")$("#autoCloseModal #autoCloseModalBody").html(msg);//两秒后消失se…