fastapi写登录注册页面前后端代码
时间: 2024-06-04 15:04:51 浏览: 245
FastAPI是一个快速构建API的Python框架,其主要特点是高性能、易于使用和快速编写。在FastAPI中,可以使用Python的异步功能来提高性能,同时可以使用Pydantic来实现数据验证和文档生成。下面是FastAPI编写登录注册页面前后端代码的简要介绍。
后端代码:
首先需要安装FastAPI和uvicorn,可以使用pip进行安装:
```
pip install fastapi uvicorn
```
然后创建一个main.py文件,编写以下代码:
```python
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from passlib.context import CryptContext
from datetime import datetime, timedelta
from jose import JWTError, jwt
app = FastAPI()
# 设置跨域资源共享(CORS)中间件,允许前端跨域访问
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 设置加密算法
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# 设置JWT相关参数
SECRET_KEY = "secret"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# 定义用户模型类
class User():
def __init__(self, username, hashed_password):
self.username = username
self.hashed_password = hashed_password
# 假设存在一个用户列表users
users = [
User(username="user1", hashed_password=pwd_context.hash("password1")),
User(username="user2", hashed_password=pwd_context.hash("password2")),
]
# 获取用户信息函数
def get_user(username: str):
for user in users:
if user.username == username:
return user
return None
# 验证密码函数
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
# 创建access_token函数
def create_access_token(data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
# 定义OAuth2密码模式对象
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")
# 定义登录路由
@app.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = get_user(form_data.username)
if not user:
raise HTTPException(status_code=400, detail="用户名或密码错误")
if not verify_password(form_data.password, user.hashed_password):
raise HTTPException(status_code=400, detail="用户名或密码错误")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
# 定义获取用户信息路由
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise HTTPException(status_code=401, detail="无效凭证")
except JWTError:
raise HTTPException(status_code=401, detail="无效凭证")
user = get_user(username)
if user is None:
raise HTTPException(status_code=404, detail="用户不存在")
return {"username": user.username}
```
前端代码:
前端代码可以使用Vue.js来实现,需要使用axios库来发送HTTP请求。首先需要安装Vue.js和axios库,可以使用npm进行安装:
```
npm install vue axios
```
然后创建一个App.vue文件,编写以下代码:
```html
<template>
<div>
<div v-if="!isLoggedIn">
<h3>登录</h3>
<form @submit.prevent="login">
<label>
用户名:
<input type="text" v-model="username">
</label>
<br>
<label>
密码:
<input type="password" v-model="password">
</label>
<br>
<button type="submit">登录</button>
</form>
<p v-if="loginError">{{ loginError }}</p>
</div>
<div v-else>
<h3>欢迎 {{ username }}</h3>
<button @click="logout">退出登录</button>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
isLoggedIn: false,
username: '',
password: '',
token: '',
loginError: ''
}
},
methods: {
async login () {
try {
const response = await axios.post('http://localhost:8000/login', {
username: this.username,
password: this.password
})
this.token = response.data.access_token
localStorage.setItem('token', this.token)
this.isLoggedIn = true
} catch (error) {
this.loginError = error.response.data.detail
}
},
logout () {
localStorage.removeItem('token')
this.isLoggedIn = false
this.username = ''
this.password = ''
this.token = ''
this.loginError = ''
},
async getUserInfo () {
try {
const response = await axios.get('http://localhost:8000/users/me', {
headers: { Authorization: `Bearer ${this.token}` }
})
this.username = response.data.username
this.isLoggedIn = true
} catch (error) {
localStorage.removeItem('token')
this.isLoggedIn = false
}
}
},
created () {
const token = localStorage.getItem('token')
if (token) {
this.token = token
this.getUserInfo()
}
}
}
</script>
```
以上就是使用FastAPI和Vue.js编写登录注册页面前后端代码的简要介绍,当然实际项目中还需要考虑更多的安全问题和业务逻辑。
阅读全文