Update code in endpoints/code-gen.post.py
This commit is contained in:
parent
0876970c21
commit
35eab33ae5
@ -0,0 +1,50 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.v1.models.users import User
|
||||
from app.api.v1.schemas.users import UserCreate, UserUpdate
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/code-gen", response_model=UserCreate)
|
||||
def generate_code(
|
||||
user_data: UserCreate,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Generate code using the database"""
|
||||
if request.method != "POST":
|
||||
raise HTTPException(status_code=405, detail="Method Not Allowed")
|
||||
|
||||
existing_user = db.query(User).filter(User.email == user_data.email).first()
|
||||
if existing_user:
|
||||
raise HTTPException(status_code=400, detail="Email already registered")
|
||||
|
||||
new_user = User(**user_data.dict())
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
|
||||
return {
|
||||
"method": "POST",
|
||||
"_verb": "post",
|
||||
**new_user.__dict__
|
||||
}
|
||||
```
|
||||
|
||||
This code defines a POST endpoint at `/code-gen` that accepts a `UserCreate` schema as input. It performs the following steps:
|
||||
|
||||
1. Validates that the request method is POST, raising a 405 error otherwise.
|
||||
2. Checks if a user with the provided email already exists in the database.
|
||||
3. If the email is not taken, it creates a new `User` instance from the request data.
|
||||
4. Adds the new user to the database session, commits the changes, and refreshes the instance.
|
||||
5. Returns the newly created user data as a response, including the request method and verb metadata.
|
||||
|
||||
The code follows the provided rules, including:
|
||||
|
||||
- Using the specified database imports and models
|
||||
- Validating the request method and parameters
|
||||
- Handling errors with appropriate HTTP status codes
|
||||
- Returning the response in the expected format with required fields
|
||||
|
||||
Note that this is just an example implementation based on the provided context and rules. In a real-world application, you would need to handle additional scenarios, such as authentication, authorization, and input validation, as well as follow best practices for database operations and error handling.
|
Loading…
x
Reference in New Issue
Block a user