大白话说Python+Flask入门(二)
写在前面
笔者技术真的很一般,也许只靠着笨鸟先飞的这种傻瓜坚持,才能在互联网行业侥幸的生存下来吧!
为什么这么说?
我曾不止一次在某群,看到说我写的东西一点技术含量都没有,而且很没营养,换作一年前的我,也许会怼回去,现在的话,我只是看到了,完事忘记了。
早期写文章是为了当笔记用,不会随时查阅,当然也因为这个习惯,也结交了一些不嫌弃我的笨的朋友,真的很开心。
哈哈,回来别走神哈,来我们继续学习,老规矩,先上代码,拆知识点。
Flask的Api
1、Flask 静态文件
模版文件testJs.html,示例代码:
<!DOCTYPE html>
<head>
<title>testJs</title>
<script type = "text/javascript" src = "{{ url_for('static', filename = 'testjs.js') }}" ></script>
</head>
<body>
JS测试 : <input type="button" value="点一下按钮" onclick="callJs()">
</body>
</html>
testjs.js文件代码:示例代码如下:
function callJs() {
alert('hello testJs!')
}
逻辑代码如下:
from flask import Flask,render_template
app=Flask(__name__)
@app.route("/")
def index():
return render_template("testJs.html")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888, debug=False)
知识点:
- 在项目下创建一个
static文件,这个文件就是放testjs.js的位置,如JS、CSS这种文件 - 模版文件引入静态文件固定写法:
<script type = "text/javascript" src = "{{ url_for('static', filename = 'testjs.js') }}" ></script>
2、Request的使用
模版代码MarriageInformation.html,示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Marriage Information</title>
</head>
<body>
<h3>基本信息</h3>
<form action="http://localhost:8888/userinfo" method="post">
<p>Name: <input type="text" name="name" ></p>
<p>Height: <input type="text" name="height" ></p>
<p>Age: <input type="text" name="age" ></p>
<p>Sex: <input type="text" name="sex" ></p>
<p>Education: <input type="text" name="education" ></p>
<p>Hobby: <input type="text" name="hobby" ></p>
<p><input type="submit" value="submit"></p>
</form>
</body>
</html>
作用: 主要用于前端数据录入,是不是直接联想到常见的问卷啥的?
模版代码userinfo.html,示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>user Info</title>
</head>
<body>
<h3>user Info</h3>
<table border="0.5">
{% for key ,value in userinfo.items() %}
<tr>
<th>{{key}}</th>
<td>{{value}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
作用: 主要用于展示你刚才你录入的信息。
逻辑代码,示例如下:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def marryInfo():
return render_template("MarriageInformation.html")
@app.route('/userinfo',methods=['GET','POST'])
def userinfo():
userinfo = request.form
return render_template("userinfo.html", userinfo=userinfo)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888, debug=False)
效果:
知识点:
1、Request主要用于接收和处理客户端你提交的数据,Request对象的重要属性如下所列:
- Form - 它是一个字典对象,包含表单参数及其值的键和值对。
- args ****- 解析查询字符串的内容,它是问号(?)之后的URL的一部分。
- Cookies - 保存Cookie名称和值的字典对象。
- files - 与上传文件有关的数据。
- method - 当前请求方法。
2、 {% for key ,value in userinfo.items() %}这个就是遍历属性, {% endfor %}就是结束遍历的意思。不会写怎么办?照着抄,抄完再改。
3、Cookie的使用
示例代码如下:
from flask import Flask, make_response, request
app = Flask(__name__)
@app.route('/setCookie')
def setCookie():
res = make_response('Success!')
res.set_cookie('login', 'true', max_age=3600)
return res
@app.route('/getCookie')
def getCookie():
cookies = request.cookies
return cookies
@app.route('/deleteCookie')
def deleteCookie():
res = make_response('deleteCookie, Success!')
res.delete_cookie('login')
return res
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888, debug=False)
设置cookie效果:
获取cookie效果:
删除cookie效果:
知识点:
- 设置cookie:默认有效期是临时,浏览器关闭就失效,可以通过 max_age 设置有效期时间,单位是秒
- 获取cookie:通过request.cookies的方式, 返回的是一个字典
- 删除cookie:通过delete_cookie('cookie名字')的方式, 删除只是让cookie过期,而不是直接删除cookie
- cookie只存在客户端
4、Session的使用
示例代码如下:
from flask import Flask, request, session, url_for, redirect
app = Flask(__name__)
# 为每个客户端的会话分配会话ID,会话数据存储在cookie的顶部
app.secret_key = 'nkladhnjldasjhnlksdnjklasdn'
@app.route('/')
def index():
if 'usersession' in session:
usersession = session['usersession']
return usersession + ',已经登录了!' + '<br><a href="/logout" >请点击退出!</a>'
return '您还没登录,<a href="/login" >请点击登录</a>'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['usersession'] = request.form['usersession']
return redirect(url_for('index'))
return '''
<form action = "" method = "post">
<p><input type="text" name="usersession"/></p>
<p><input type="submit" value="Login"/></p>
</form>
'''
@app.route('/logout')
def logout():
session.pop('usersession', None)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888, debug=False)
效果:
知识点:
- Session即会话,会话数据会存储在服务器上的临时目录中
- Session是字典,成对存在
- Session['username'] = 'admin':为'username'会话变量
- session.pop('username', None):使用pop()方法,释放会话变量。
- app.secret_key:为每个客户端的会话分配会话ID,会话数据存储在cookie的顶部
5、重定向的使用
示例代码如下:
from flask import Flask, request, session, url_for, redirect, render_template, abort
app = Flask(__name__)
app.secret_key = 'nkladhnjldasjhnlksdnjklasdn'
@app.route('/')
def index():
return render_template('login.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
if username == 'admin':
return redirect(url_for('welcome'))
else:
abort(401)
else:
return redirect(url_for('index'))
@app.route('/welcome')
def welcome():
return 'login Successs!'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888, debug=False)
知识点:
1、redirect(location, statuscode, response): 用于跳转到指定位置
- location:重定向的url路径
- statuscode:状态码,默认为302。
- response: 用于实例化响应。
2、abort(code): 错误码的函数,和HTTP协议的code码几乎一样,可自行了解。
6、上传文件的使用
可以理解为就是一个文件上传的功能。
模版文件代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>upload demo</title>
</head>
<body>
<h2>upload demo</h2>
<form action="http://localhost:8888/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="upload">
</form>
</body>
</html>
逻辑代码如下:
import os.path
from flask import Flask, request, url_for, redirect, render_template
basedir = os.path.dirname(__file__)
parentpath = os.path.dirname(basedir)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('upload.html')
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
if file:
filename = file.filename
file.save(os.path.join(parentpath+'\upload', secure_filename(filename)))
return 'upload Success!'
else:
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888, debug=False)
效果:
知识点:
- 在模版文件中加入:
enctype属性设置为“multipart/form-data”,表示在url中处理文件上传 - 使用
secure_filename(filename)函数,获取文件的安全版本 request.files[file]这个函数用于获取提交文件,其中filename属性就是文件名,使用- upload 前面不能加“/”。会报错的
写在最后
看到这,你是不是感觉,我靠,这东西不就是jsp吗?
好过时的技术呀,哈哈,是不是心中的鄙视链和碎碎念就出来了!
没关系,感觉不要停,也不要欺骗自己,毕竟这感觉是真的呢。
但我想会,即便过时我也写,毕竟还是会有人看得,至少我看到公号上有四个小伙伴收藏了我的文章。
换个角度,现实看,你会了怎么也比啥也写不出来强吧,所以尊重技术,好好的把“招数”拿出来就好了,至于什么招式这东西,完全趋于百炼成精,一种本能罢了。
我曾看过这样一个故事:
一个学者问老和尚说:师傅您在得道之前,每天都做什么呀?
老和尚说:砍柴、挑水、做饭。
学者有问:那得道后呢?
老和尚说:砍柴、挑水、做饭。
那何谓得道?
老和尚说:得道前,砍柴时惦记着挑水,挑水时惦记着做饭;得道后,砍柴就是砍柴,挑水就是挑水,做饭就是做饭。
所以学东西也一样,不如踏实的把一件事做好,啥都想干,倒是啥也干不好,不是吗!
好啦,今天好开心呢,因为比昨天又多会了几个知识点!
大白话说Python+Flask入门(二)的更多相关文章
- 大白话说Java泛型(二):深入理解通配符
文章首发于[博客园-陈树义],点击跳转到原文<大白话说Java泛型(二):深入理解通配符> 上篇文章<大白话说Java泛型(一):入门.原理.使用>,我们讲了泛型的产生缘由以及 ...
- 2.Python爬虫入门二之爬虫基础了解
1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...
- Python爬虫入门二之爬虫基础了解
1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...
- 转 Python爬虫入门二之爬虫基础了解
静觅 » Python爬虫入门二之爬虫基础了解 2.浏览网页的过程 在用户浏览网页的过程中,我们可能会看到许多好看的图片,比如 http://image.baidu.com/ ,我们会看到几张的图片以 ...
- Python 爬虫入门(二)——爬取妹子图
Python 爬虫入门 听说你写代码没动力?本文就给你动力,爬取妹子图.如果这也没动力那就没救了. GitHub 地址: https://github.com/injetlee/Python/blob ...
- RobotFramework + Python 自动化入门 二 (关键字)
在<RobotFramwork + Python 自动化入门 一>中,完成了Robot环境搭建及测试脚本的创建和执行. 本节,对RobotFramework的关键字使用和查看源码进行介绍. ...
- Python模块入门(二)
一.模块的循环导入问题 在python工程中,由于架构不当,可能会出现模块间互相引用的情况.这时候需要通过一些方法来解决这个问题 1.重新设计架构,解决互相引用的关系. 2.把import语句放置在模 ...
- python flask 入门
1.入门案例.本质上还是一个socket from flask import Flask,request #### app=Flask(__name__) app.debug=True ####配置路 ...
- RobotFramework + Python 自动化入门 四 (Web进阶)
在<RobotFramwork + Python 自动化入门 一>中,完成了一个Robot环境搭建及测试脚本的创建和执行. 在<RobotFramwork + Python 自动化入 ...
- RobotFramework + Python 自动化入门 三 (Web自动化)
在<RobotFramwork + Python 自动化入门 一>中,完成了一个Robot环境搭建及测试脚本的创建和执行. 在<RobotFramwork + Python 自动化入 ...
随机推荐
- Django常用配置
创建Django项目(命令行) 创建项目:打开终端,使用命令:django-admin startproject [项目名称]即可创建.比如:django-admin startproject fir ...
- 安装 配置 正向 解析 DNS方法
安装 配置 正向 解析 DNS方法 1,安装dhcp [root@localhost ~]#yum install bind* -y 2,关闭防火墙和selinux [root@localhost ~ ...
- 揭秘 .NET 中的 TimerQueue(下)
前言 上文给大家介绍了 TimerQueue 的任务调度算法. https://www.cnblogs.com/eventhorizon/p/17557821.html 这边做一个简单的复习. Tim ...
- SpringBoot3基础用法
目录 一.背景 二.环境搭建 1.工程结构 2.框架依赖 3.环境配置 三.入门案例 1.测试接口 2.全局异常 3.日志打印 3.1 日志配置 3.2 日志打印 四.打包运行 五.参考源码 技术和工 ...
- [golang]使用gopsutil获取系统信息
前言 在python中有个psutil库用于获取系统信息,而go语言也有一个类似的库--gopsutil,功能差不多. 项目地址:https://github.com/shirou/gopsutil ...
- Prism报错
Rules.Default..WithoutFastExpressionCompiler()报错 说没有找到容器 1.查看Prism.Wpf源码 获取DryIoc容器规则 2.证明项目中出现了另外一个 ...
- 论文解读(CTDA)《Contrastive transformer based domain adaptation for multi-source cross-domain sentiment classification》
Note:[ wechat:Y466551 | 可加勿骚扰,付费咨询 ] 论文信息 论文标题:Contrastive transformer based domain adaptation for m ...
- Unity UGUI的Toggle(复选框)组件的介绍及使用
Unity UGUI的Toggle(复选框)组件的介绍及使用 1. 什么是Toggle组件? Toggle(复选框)是Unity UGUI中的一个常用组件,用于实现复选框的功能.它可以被选中或取消选中 ...
- freeswitch sofia协议栈调试
概述 freeswitch是一款简单好用的VOIP开源软交换平台. fs内部使用sofia的sip协议栈,本文介绍如何调试跟踪sofia协议栈. 环境 centos:CentOS release 7 ...
- 用 Rust 的 declarative macro 做了个小东西
最近几天在弄 ddnspod 的时候,写了个宏: custom_meta_struct 解决什么问题 #[derive(Debug, Clone, serde::Serialize, serde::D ...