大白话说Python+Flask入门(二)

写在前面

笔者技术真的很一般,也许是只靠着笨鸟先飞的这种傻瓜坚持 ,才能在互联网行业侥幸的生存下来吧!

为什么这么说?

我曾不止一次在某群,看到说我写的东西一点技术含量都没有,而且很没营养,换作一年前的我,也许会怼回去,现在的话,我只是看到了,完事忘记了。

早期写文章是为了当笔记用,不会随时查阅,当然也因为这个习惯,也结交了一些不嫌弃我的笨的朋友,真的很开心。

哈哈,回来别走神哈,来我们继续学习,老规矩,先上代码,拆知识点。

Flask的Api

1、Flask 静态文件

模版文件testJs.html,示例代码:

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文件代码:示例代码如下:

js 复制代码
function callJs() {
  alert('hello testJs!')
}

逻辑代码如下:

python 复制代码
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这种文件
  • 模版文件引入静态文件固定写法:
js 复制代码
<script type = "text/javascript" src = "{{ url_for('static', filename = 'testjs.js') }}" ></script>

2、Request的使用

模版代码MarriageInformation.html,示例代码如下:

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,示例代码如下:

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>

作用: 主要用于展示你刚才你录入的信息。

逻辑代码,示例如下:

python 复制代码
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的使用

示例代码如下:

python 复制代码
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的使用

示例代码如下:

python 复制代码
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、重定向的使用

示例代码如下:

python 复制代码
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、上传文件的使用

可以理解为就是一个文件上传的功能。

模版文件代码:

html 复制代码
<!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>

逻辑代码如下:

python 复制代码
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吗?

好过时的技术呀,哈哈,是不是心中的鄙视链和碎碎念就出来了!

没关系,感觉不要停,也不要欺骗自己,毕竟这感觉是真的呢。

但我想会,即便过时我也写 ,毕竟还是会有人看得,至少我看到公号上有四个小伙伴收藏了我的文章。

换个角度,现实看,你会了怎么也比啥也写不出来强吧,所以尊重技术,好好的把"招数"拿出来就好了,至于什么招式这东西,完全趋于百炼成精,一种本能罢了。

我曾看过这样一个故事:

一个学者问老和尚说:师傅您在得道之前,每天都做什么呀?

老和尚说:砍柴、挑水、做饭。

学者有问:那得道后呢?

老和尚说:砍柴、挑水、做饭。

那何谓得道?

老和尚说:得道前,砍柴时惦记着挑水,挑水时惦记着做饭;得道后,砍柴就是砍柴,挑水就是挑水,做饭就是做饭。

所以学东西也一样,不如踏实的把一件事做好,啥都想干,倒是啥也干不好,不是吗!

好啦,今天好开心呢,因为比昨天又多会了几个知识点!

相关推荐
uzong2 小时前
技术故障复盘模版
后端
GetcharZp3 小时前
基于 Dify + 通义千问的多模态大模型 搭建发票识别 Agent
后端·llm·agent
桦说编程3 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
IT毕设实战小研3 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi4 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
阿华的代码王国5 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
Jimmy5 小时前
AI 代理是什么,其有助于我们实现更智能编程
前端·后端·ai编程
AntBlack5 小时前
不当韭菜V1.1 :增强能力 ,辅助构建自己的交易规则
后端·python·pyqt
bobz9656 小时前
pip install 已经不再安全
后端
寻月隐君6 小时前
硬核实战:从零到一,用 Rust 和 Axum 构建高性能聊天服务后端
后端·rust·github