当前位置:   article > 正文

天雨流芳--使用 Python+Vue3 来构建一个博客(一)_vue可以内嵌python吗

vue可以内嵌python吗

天雨流芳–使用 Python+Vue3 来构建一个博客(一)

引言:

练习时常一年半的前端切图仔想学后端,感觉现在有gtp真的是大大大大降低了新语言的学习成本,gtp就像一个24小时能回答你基本上所有问题的老师,乘此速速学习,顺便记录下 天雨流芳

tip:“天雨流芳”是纳西语音译语,行云流水般书写在丽江木府旁的一座牌坊上,其纳西语音意为“读书去吧”

立个小目标 :

1、vue + fastapi的管理平台 vue3 +ts 代码必须必须规整 看起来舒服

2、帅气逼人的博客页 打算永原生js写,想要seo,不然不知道还有啥方案,各位大佬看到可以支支招

3、如果有任何问题 或者任何可以写更好更精炼代码的地方 希望大佬们能指点指点,主打一个,听劝、求知!!!!!

1、项目结构

├── blog/
│   ├── api/ # 接口路由定义
│   │   ├── __init__.py
│   │   ├── user_api.py
│   │   └── ...
│   │
│   ├── core/ # 核心代码模块
│   │   ├── __init__.py
│   │   ├── db.py
│   │   └── ...
│   │
│   ├── models/ # 数据模型
│   │   ├── __init__.py
│   │   ├── user_models.py
│   │   └── ...
│   │
│   ├── service/ # 功能实现
│   │   ├── __init__.py
│   │   └── ...
│   │
│   ├── tools/ # 其它工具类
│   │   ├── __init__.py
│   │   └── ...
│   │
│   ├── main.py
│   ├── requirements.txt
│   └── ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

2、搭建mysql连接

# 路径 /core/db.py
import mysql.connector.pooling


class Database:
    _pool = None

    # 连接池配置参数
    _pool_config = {
        "pool_name": "my_pool",
        "pool_size": 5,
        "pool_reset_session": True,
        "host": "localhost",
        "user": "******",
        "password": "******",
        "database": "******"
    }

    def __init__(self):
        if not Database._pool:
            Database._pool = mysql.connector.pooling.MySQLConnectionPool(**Database._pool_config)

    def insert_data(self, query, values):
        with self._get_connection() as connection:
            cursor = connection.cursor()
            cursor.execute(query, values)
            connection.commit()

    def find_data(self, query):
        with self._get_connection() as connection:
            cursor = connection.cursor()
            cursor.execute(query)
            result = cursor.fetchall()
        return result

    def _get_connection(self):
        return Database._pool.get_connection()

    def _release_connection(self, connection):
        connection.close()

    def __enter__(self):
        self._connection = self._get_connection()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self._release_connection(self._connection)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

封装一个mysql工具类,先简单封装两个方法,用来插入和查询。具体使用在添加路由模块中展示

3、添加路由模块

# 路径 /api/user_api.py
from fastapi import APIRouter, HTTPException
from models.user_model import CreateUser
from service.user_server import User

router = APIRouter(
    prefix="/user",
    tags=["user"],
)
user = User()


@router.get("/")
def get_user():
    result = user.get_users()
    if result:
        return result
    else:
        raise HTTPException(status_code=404, detail="No users found")


@router.post('/add')
def add_user(request: CreateUser):
    result = user.create_user(request)
    return result

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

fastapi中 使用路由模块需要在main.py中定义各路由的路径,但是当模块非常多的时候,如果全写在main.py中就会导致非常的臃肿,还难维护,所以引入APIRouter 处理多程序分类对我来说是必要的,就像flask里蓝图一样。注册号子模块后还需要到main.py文件中导入注册

# 路径 /main.py
from fastapi import FastAPI
from api import user_api

app = FastAPI()

app.include_router(user_api.router)
# 然后就可以访 http://localhost:端口号/user  查询users表下所有数据

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4、插入数据&&参数校验

1)、api入口函数

# 路径 /api/user_api.py
@router.post('/add')
def add_user(request: CreateUser = Body(...)):
    try:
        request = user.create_user(request)
        return create_response(code=200, msg='success', data=request)
    except HTTPException as e:
        error_detail = e.detail
        return {"error_message": error_detail}
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2)、参数校验模型

# 路径 /models/user_model.py
from pydantic import BaseModel, Field
from typing import Optional

class CreateUser(BaseModel):
    username: str = Field(..., min_length=1, max_length=50, description='用户名', example="yu lon")
    password: str = Field(..., min_length=1, max_length=255, description='密码', example='123456')
    email: Optional[str] = Field(None, min_length=1, max_length=100, description='邮箱', example='123456@qq.com')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3)、数据库具体操作

# 路径 /service/user_server.py
from core.db import Database
from tools.time import get_current_time
from tools.uuid import use_uuid


class User:
    def __init__(self):
        self.db = Database()

    def get_users(self):
        query = "SELECT * FROM users"
        result = self.db.find_data(query)
        if result:
            return {"user": result}

    def create_user(self, data):
        _uuid = use_uuid()
        _username = data.username
        _password = data.password
        _email = data.email
        _create_time = get_current_time()
        query = "INSERT INTO users (user_id, username, password, email, created_at) VALUES (%s, %s, %s, %s, %s)"
        values = (_uuid, _username, _password, _email, _create_time)
        self.db.insert_data(query, values)
        return {"user_id": _uuid, "username": _username}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

end:中途学到的一些东西

1)、位置参数和关键词参数

在看封装数据返回格式的时候看到一个代码是这样写的,就疑惑参数里单走一个*号是啥意思,浅浅去学习了下,如下:

def greet(*,name, message):
    print(f"Hello, {name}! {message}")

greet("Alice", "How are you?") # error TypeError: create_response() takes 0 positional arguments but 2 were given 报错表示两个意外参数
greet(name="Alice",message="How are you?")# true  换成关键词参数就对了
  • 1
  • 2
  • 3
  • 4
  • 5

位置参数(Positional Arguments):

位置参数是指按照参数在函数定义中的顺序传递参数的方式。这意味着第一个参数值将被分配给函数定义的第一个参数,第二个参数值将被分配给函数定义的第二个参数,以此类推。示例:

def greet(name, message):
    print(f"Hello, {name}! {message}")

greet("Alice", "How are you?")
  • 1
  • 2
  • 3
  • 4

在上述示例中,“Alice” 被传递给 name 参数,“How are you?” 被传递给 message 参数,这是位置参数的用法。

关键字参数(Keyword Arguments):

def greet(name, message):
    print(f"Hello, {name}! {message}")

greet(message="How are you?", name="Bob")
  • 1
  • 2
  • 3
  • 4

在上述示例中,参数名称被用于明确指定哪个参数应该获得哪个值,这是关键字参数的用法。

**总结:**关键字参数通常更具可读性,特别是在函数有多个参数或者参数的顺序容易混淆的情况下。它们还提供了更大的灵活性,因为你可以以不同的顺序传递参数,并且可以忽略某些参数。位置参数在函数定义中的顺序是固定的,因此传递参数时必须按照这个顺序。

下一步:

1、在完善好response的封装

2、加上token认证,加密啥啥啥的

3、再看看还差啥 框架搭好

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/975460
推荐阅读
相关标签
  

闽ICP备14008679号