Advertisement
Kool_Cool

Untitled

Aug 12th, 2024
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.15 KB | None | 0 0
  1. To convert your Django-based code into a FastAPI application, you need to follow these steps:
  2.  
  3. 1. **Define Data Models**: Define the Pydantic models for request and response data.
  4. 2. **Set Up Database Connection**: Use an ORM like SQLAlchemy for database operations.
  5. 3. **Create API Endpoints**: Implement FastAPI endpoints to handle requests.
  6. 4. **Handle Data Processing**: Use appropriate libraries and methods to process and return the data.
  7.  
  8. Here’s how you can convert the given Django code to FastAPI:
  9.  
  10. ### Step 1: Define Data Models
  11.  
  12. You'll need to define Pydantic models for request validation and response serialization.
  13.  
  14. ```python
  15. from pydantic import BaseModel
  16. from typing import Optional, List
  17.  
  18. class ReportRequest(BaseModel):
  19. created_date_min: str
  20. created_date_max: str
  21. trade_security__trade_exchange: str
  22. trade_security__client: str
  23.  
  24. class ReportResponse(BaseModel):
  25. trade_date: str
  26. trade_security_no: str
  27. expiry_date: Optional[str]
  28. instrument_type: Optional[str]
  29. symbol: Optional[str]
  30. exchange_id: Optional[str]
  31. trade_security_type_enum_id: Optional[str]
  32. trade_tr: Optional[str]
  33. trade_sr: Optional[str]
  34. trade_no: Optional[str]
  35. buy_sell_opt: Optional[str]
  36. order_time: Optional[str]
  37. quantity: Optional[int]
  38. rate: Optional[float]
  39. brokerage_total: Optional[float]
  40. net_rate: Optional[float]
  41. amount: Optional[float]
  42. turnover: Optional[float]
  43. stt: Optional[float]
  44. sebi: Optional[float]
  45. service_tax: Optional[float]
  46. stamp_duty: Optional[float]
  47. clear_charge: Optional[float]
  48. ```
  49.  
  50. ### Step 2: Set Up Database Connection
  51.  
  52. You can use SQLAlchemy for database operations. Define the database models and create a session:
  53.  
  54. ```python
  55. from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Date, DateTime, Numeric
  56. from sqlalchemy.ext.declarative import declarative_base
  57. from sqlalchemy.orm import sessionmaker, relationship
  58. from fastapi import FastAPI, HTTPException
  59.  
  60. DATABASE_URL = "postgresql://user:password@localhost/dbname"
  61. engine = create_engine(DATABASE_URL)
  62. SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  63. Base = declarative_base()
  64.  
  65. class TradeDetail(Base):
  66. __tablename__ = "trade_detail"
  67. id = Column(Integer, primary_key=True, index=True)
  68. client_id = Column(String)
  69. trade_exchange_id = Column(String)
  70. # Define other fields and relationships
  71.  
  72. class TradeDetailItem(Base):
  73. __tablename__ = "trade_detail_item"
  74. id = Column(Integer, primary_key=True, index=True)
  75. trade_security_id = Column(Integer, ForeignKey("trade_detail.id"))
  76. trade_sr = Column(String)
  77. trade_tr = Column(String)
  78. # Define other fields and relationships
  79.  
  80. trade_security = relationship("TradeDetail")
  81. ```
  82.  
  83. ### Step 3: Create FastAPI Endpoints
  84.  
  85. Define FastAPI endpoints that interact with your database and return data.
  86.  
  87. ```python
  88. from fastapi import FastAPI, Depends, Query
  89. from sqlalchemy.orm import Session
  90. from datetime import datetime
  91.  
  92. app = FastAPI()
  93.  
  94. def get_db():
  95. db = SessionLocal()
  96. try:
  97. yield db
  98. finally:
  99. db.close()
  100.  
  101. @app.post("/generate-report", response_model=List[ReportResponse])
  102. def generate_report(request: ReportRequest, db: Session = Depends(get_db)):
  103. Today = datetime.today().date()
  104. fin_year_start = get_financial_year_date() # Implement this function
  105. date_first = request.created_date_min
  106. date_second = request.created_date_max
  107.  
  108. date_first_obj = datetime.strptime(date_first, "%Y-%m-%d").date()
  109. date_second_obj = datetime.strptime(date_second, "%Y-%m-%d").date()
  110.  
  111. exchange = request.trade_security__trade_exchange
  112. client_id = request.trade_security__client
  113.  
  114. # Convert dates as needed
  115. if date_first:
  116. date_begin = datetime.strptime(date_first, "%Y-%m-%d").strftime('%Y-%m-%d')
  117. date_end = datetime.strptime(date_second, "%Y-%m-%d").strftime('%Y-%m-%d')
  118. else:
  119. date_begin = datetime.strptime(fin_year_start, "%d.%m.%Y").strftime('%Y-%m-%d')
  120. date_end = datetime.strptime(Today, "%d.%m.%Y").strftime('%Y-%m-%d')
  121.  
  122. # Query database
  123. trdMainObj = db.query(TradeDetailItem).join(TradeDetail).filter(
  124. TradeDetail.client_id == client_id,
  125. TradeDetail.trade_exchange_id == exchange,
  126. TradeDetailItem.trade_date.between(date_begin, date_end)
  127. ).all()
  128.  
  129. if not trdMainObj:
  130. raise HTTPException(status_code=404, detail="No records found")
  131.  
  132. return trdMainObj
  133. ```
  134.  
  135. ### Step 4: Handle Data Processing
  136.  
  137. If you need to process the data or convert it to a specific format, handle it in the endpoint or in a utility function.
  138.  
  139. ```python
  140. def convert_to_dict(data):
  141. # Convert SQLAlchemy results to dict
  142. return [{col.name: getattr(row, col.name) for col in row.__table__.columns} for row in data]
  143. ```
  144.  
  145. ### Complete Example
  146.  
  147. Here’s a complete example integrating all parts:
  148.  
  149. ```python
  150. from fastapi import FastAPI, HTTPException, Depends
  151. from sqlalchemy.orm import Session
  152. from pydantic import BaseModel
  153. from datetime import datetime
  154. from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Date, DateTime, Numeric
  155. from sqlalchemy.ext.declarative import declarative_base
  156. from sqlalchemy.orm import sessionmaker, relationship
  157. from typing import List, Optional
  158.  
  159. # Database Setup
  160. DATABASE_URL = "postgresql://user:password@localhost/dbname"
  161. engine = create_engine(DATABASE_URL)
  162. SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  163. Base = declarative_base()
  164.  
  165. class TradeDetail(Base):
  166. __tablename__ = "trade_detail"
  167. id = Column(Integer, primary_key=True, index=True)
  168. client_id = Column(String)
  169. trade_exchange_id = Column(String)
  170. # Define other fields
  171.  
  172. class TradeDetailItem(Base):
  173. __tablename__ = "trade_detail_item"
  174. id = Column(Integer, primary_key=True, index=True)
  175. trade_security_id = Column(Integer, ForeignKey("trade_detail.id"))
  176. trade_sr = Column(String)
  177. trade_tr = Column(String)
  178. trade_date = Column(Date)
  179. # Define other fields
  180.  
  181. trade_security = relationship("TradeDetail")
  182.  
  183. Base.metadata.create_all(bind=engine)
  184.  
  185. # Pydantic Models
  186. class ReportRequest(BaseModel):
  187. created_date_min: str
  188. created_date_max: str
  189. trade_security__trade_exchange: str
  190. trade_security__client: str
  191.  
  192. class ReportResponse(BaseModel):
  193. trade_date: str
  194. trade_security_no: str
  195. expiry_date: Optional[str]
  196. instrument_type: Optional[str]
  197. symbol: Optional[str]
  198. exchange_id: Optional[str]
  199. trade_security_type_enum_id: Optional[str]
  200. trade_tr: Optional[str]
  201. trade_sr: Optional[str]
  202. trade_no: Optional[str]
  203. buy_sell_opt: Optional[str]
  204. order_time: Optional[str]
  205. quantity: Optional[int]
  206. rate: Optional[float]
  207. brokerage_total: Optional[float]
  208. net_rate: Optional[float]
  209. amount: Optional[float]
  210. turnover: Optional[float]
  211. stt: Optional[float]
  212. sebi: Optional[float]
  213. service_tax: Optional[float]
  214. stamp_duty: Optional[float]
  215. clear_charge: Optional[float]
  216.  
  217. # FastAPI App
  218. app = FastAPI()
  219.  
  220. def get_db():
  221. db = SessionLocal()
  222. try:
  223. yield db
  224. finally:
  225. db.close()
  226.  
  227. @app.post("/generate-report", response_model=List[ReportResponse])
  228. def generate_report(request: ReportRequest, db: Session = Depends(get_db)):
  229. Today = datetime.today().date()
  230. fin_year_start = get_financial_year_date() # Implement this function
  231. date_first = request.created_date_min
  232. date_second = request.created_date_max
  233.  
  234. date_first_obj = datetime.strptime(date_first, "%Y-%m-%d").date()
  235. date_second_obj = datetime.strptime(date_second, "%Y-%m-%d").date()
  236.  
  237. exchange = request.trade_security__trade_exchange
  238. client_id = request.trade_security__client
  239.  
  240. # Convert dates as needed
  241. if date_first:
  242. date_begin = datetime.strptime(date_first, "%Y-%m-%d").strftime('%Y-%m-%d')
  243. date_end = datetime.strptime(date_second, "%Y-%m-%d").strftime('%Y-%m-%d')
  244. else:
  245. date_begin = datetime.strptime(fin_year_start, "%d.%m.%Y").strftime('%Y-%m-%d')
  246. date_end = datetime.strptime(Today, "%d.%m.%Y").strftime('%Y-%m-%d')
  247.  
  248. # Query database
  249. trdMainObj = db.query(TradeDetailItem).join(TradeDetail).filter(
  250. TradeDetail.client_id == client_id,
  251. TradeDetail.trade_exchange_id == exchange,
  252. TradeDetailItem.trade_date.between(date_begin, date_end)
  253. ).all()
  254.  
  255. if not trdMainObj:
  256. raise HTTPException(status_code=404, detail="No records found")
  257.  
  258. return trdMainObj
  259. ```
  260.  
  261. ### Summary
  262.  
  263. - **Data Models**: Define models with Pydantic for request validation and response serialization.
  264. - **Database Connection**: Use SQLAlchemy for database operations.
  265. - **API Endpoints**: Create FastAPI endpoints to handle requests
  266.  
  267. and return responses.
  268. - **Data Processing**: Convert SQLAlchemy results to dictionaries as needed.
  269.  
  270. This FastAPI application should give you a good starting point for migrating from Django to FastAPI. Adjust the code as necessary based on your specific requirements and database schema.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement