初始化项目:models+fastapi登录示例
This commit is contained in:
commit
13c317e80c
8
.idea/.gitignore
vendored
Normal file
8
.idea/.gitignore
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
# 默认忽略的文件
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# 基于编辑器的 HTTP 客户端请求
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
8
.idea/CostEvalPlatform.iml
Normal file
8
.idea/CostEvalPlatform.iml
Normal file
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
20
.idea/dataSources.xml
Normal file
20
.idea/dataSources.xml
Normal file
@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||
<data-source source="LOCAL" name="test" uuid="a5872518-f7b2-4c54-8ab8-96976a3c432a">
|
||||
<driver-ref>sqlite.xerial</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||
<jdbc-url>jdbc:sqlite:E:\pyprojects\CostEvalPlatform\test.db</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
<libraries>
|
||||
<library>
|
||||
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/xerial/sqlite-jdbc/3.45.1.0/sqlite-jdbc-3.45.1.0.jar</url>
|
||||
</library>
|
||||
<library>
|
||||
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/slf4j/slf4j-api/1.7.36/slf4j-api-1.7.36.jar</url>
|
||||
</library>
|
||||
</libraries>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
||||
53
.idea/inspectionProfiles/Project_Default.xml
Normal file
53
.idea/inspectionProfiles/Project_Default.xml
Normal file
@ -0,0 +1,53 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<Languages>
|
||||
<language minSize="110" name="Python" />
|
||||
</Languages>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="ignoredPackages">
|
||||
<value>
|
||||
<list size="6">
|
||||
<item index="0" class="java.lang.String" itemvalue="alibabacloud_tea_console" />
|
||||
<item index="1" class="java.lang.String" itemvalue="alibabacloud_tea_util" />
|
||||
<item index="2" class="java.lang.String" itemvalue="alibabacloud_alidns20150109" />
|
||||
<item index="3" class="java.lang.String" itemvalue="alibabacloud_tea_openapi" />
|
||||
<item index="4" class="java.lang.String" itemvalue="gradio" />
|
||||
<item index="5" class="java.lang.String" itemvalue="torch" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<option name="ignoredErrors">
|
||||
<list>
|
||||
<option value="E722" />
|
||||
<option value="E501" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<option name="ignoredErrors">
|
||||
<list>
|
||||
<option value="N806" />
|
||||
<option value="N802" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="ignoredIdentifiers">
|
||||
<list>
|
||||
<option value="list.*" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="SpellCheckingInspection" enabled="true" level="INFORMATION" enabled_by_default="true">
|
||||
<option name="processCode" value="true" />
|
||||
<option name="processLiterals" value="true" />
|
||||
<option name="processComments" value="true" />
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
||||
6
.idea/inspectionProfiles/profiles_settings.xml
Normal file
6
.idea/inspectionProfiles/profiles_settings.xml
Normal file
@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
32
.idea/misc.xml
Normal file
32
.idea/misc.xml
Normal file
@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="demo1" />
|
||||
</component>
|
||||
<component name="ProjectInspectionProfilesVisibleTreeState">
|
||||
<entry key="Project Default">
|
||||
<profile-state>
|
||||
<expanded-state>
|
||||
<State>
|
||||
<id>EditorConfig</id>
|
||||
</State>
|
||||
<State>
|
||||
<id>GitHub 操作</id>
|
||||
</State>
|
||||
<State>
|
||||
<id>正则表达式</id>
|
||||
</State>
|
||||
<State>
|
||||
<id>版本控制</id>
|
||||
</State>
|
||||
</expanded-state>
|
||||
<selected-state>
|
||||
<State>
|
||||
<id>用户定义</id>
|
||||
</State>
|
||||
</selected-state>
|
||||
</profile-state>
|
||||
</entry>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="demo1" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
8
.idea/modules.xml
Normal file
8
.idea/modules.xml
Normal file
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/CostEvalPlatform.iml" filepath="$PROJECT_DIR$/.idea/CostEvalPlatform.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/vcs.xml
Normal file
6
.idea/vcs.xml
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
55
main.py
Normal file
55
main.py
Normal file
@ -0,0 +1,55 @@
|
||||
from fastapi import FastAPI, HTTPException, Response, Depends
|
||||
from typing import Optional
|
||||
from datetime import datetime, timedelta
|
||||
from jose import JWTError, jwt
|
||||
from models import *
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# 创建数据库引擎
|
||||
engine = create_engine('sqlite:///test.db')
|
||||
|
||||
# 创建所有表
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
# 创建会话
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
session = SessionLocal()
|
||||
|
||||
# 用于生成和验证JWT的密钥
|
||||
SECRET_KEY = "your_secret_key"
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
|
||||
# 生成JWT token
|
||||
def create_access_token(data: dict, expires_delta: Optional[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
|
||||
|
||||
|
||||
# 登录路由
|
||||
@app.post("/api/s1/login")
|
||||
async def login(response: Response, user_data: dict):
|
||||
# 查询用户
|
||||
user = session.query(User).filter(User.name == user_data['username']).first()
|
||||
|
||||
# 验证用户名和密码
|
||||
if not user or user.password != user_data['password']:
|
||||
raise HTTPException(status_code=401, detail="Login failed")
|
||||
|
||||
# 生成JWT token
|
||||
token = create_access_token(data={"sub": user.name})
|
||||
|
||||
# 设置cookie
|
||||
response.set_cookie(key="session_token", value=token, httponly=True)
|
||||
|
||||
# 关闭数据库会话
|
||||
session.close()
|
||||
|
||||
return {"message": "Login successful"}
|
||||
50
models.py
Normal file
50
models.py
Normal file
@ -0,0 +1,50 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# @Time : 2024/11/18 下午7:00
|
||||
# @Author : 河瞬
|
||||
# @FileName: models.py
|
||||
# @Software: PyCharm
|
||||
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Enum, ForeignKey, Text
|
||||
from sqlalchemy.orm import relationship, sessionmaker, declarative_base
|
||||
from datetime import datetime
|
||||
|
||||
# 创建基类
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class Tenant(Base):
|
||||
__tablename__ = 'Tenant'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
users = relationship('User', backref='Tenant', cascade='all, delete-orphan')
|
||||
projects = relationship('Project', backref='Tenant', cascade='all, delete-orphan')
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = 'User'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
password = Column(String(100), nullable=False)
|
||||
role = Column(Integer, nullable=False) # 0: 超级管理员 1:租户管理员 2:评估员 3:审核员
|
||||
tenant_id = Column(Integer, ForeignKey('Tenant.id'), nullable=False)
|
||||
|
||||
|
||||
class Project(Base):
|
||||
__tablename__ = 'Project'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
requirement = Column(String(200), nullable=True)
|
||||
start_time = Column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
deadline = Column(DateTime, nullable=False)
|
||||
owner_id = Column(Integer, ForeignKey('Tenant.id'), nullable=False)
|
||||
# owner = relationship('Tenant', backref='projects')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 创建数据库引擎
|
||||
engine = create_engine('sqlite:///test.db')
|
||||
|
||||
# 创建所有表
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
# 创建会话
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Loading…
Reference in New Issue
Block a user