FastAPI / SQLAlchemy Create Multiple Users - sqlalchemy

I work a working API endpoint to create a single user.
#app.post("/entity/", response_model=List[schemas.User])
def create_user(user: schemas.User, db: Session = Depends(get_db)):
crud.create_user(db=db, user=user)
return JSONResponse(content={"message": "user created successfully"})
class User(BaseModel):
id: str = Field(default_factory=generate_id)
first_name: Optional[str] = ""
last_name: Optional[str] = ""
username: str
class Config:
orm_mode = True
def create_user(db: Session, user: schemas.User):
db_item = models.User(**user.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
This works, but I want to create multiple Users via one api request.
I guess the create_user function has to look somewhat like this:
def create_user(db: Session, data, user: schemas.User):
objects = []
for user in data:
db_item = models.User(**user.dict())
objects.append(dbitem)
db.bulk_save_objects(objects)
db.commit()
I just can´t my head around what is the right way to create this kind of bulkinsert

You can accept a list of users as the request body.
def create_user(db: Session, users: List[schemas.User]):
objects = []
for user in users:
db_item = models.User(**user.dict())
objects.append(dbitem)
db.bulk_save_objects(objects)
db.commit()

Related

DISCORD.PY Creating an end Giveaway Command

I am working on a giveaway bot and after doing the start and reroll command I have run into the end command , which i cannot fully grasp how to do it. I thought to register something when the giveaway is created (msgID of the giveaway im registering) in my aiosqlite database and for the end function , i could be able to fetch it and stop the giveaway. Now here is the thing, i cant think of a function or a task that will end the giveaway or somehow just end the duration.
For reference here is my start command :
class Start(commands.Cog):
def __init__(self, client):
self.client = client
def convert(self, timer):
pos = ["s", "m", "h", "d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
unit = timer[-1]
if unit not in pos:
return -1
try:
val = int(timer[:-1])
except:
return -2
return val * time_dict[unit]
#commands.command()
async def start(self, ctx, duration, winners: str, *, prize):
timer = (self.convert(duration))
winners = int(winners.replace("w",""))
await ctx.message.delete()
timestamp = time.time() + timer
epoch_time = int((time.time() + timer))
embed = discord.Embed(title = f"{prize}", description = f'React with 🎉 to enter\nEnds: <t:{epoch_time}:R> (<t:{epoch_time}>)\nHosted by {ctx.author.mention}\n', color =
ctx.author.color, timestamp=(datetime.datetime.utcfromtimestamp(timestamp)))
embed.set_footer(text=f'Winners : {winners} | Ends at \u200b')
gaw_msg = await ctx.send(content = "<:spadess:939938117736091678> **GIVEAWAY** <:spadess:939938117736091678>",embed=embed)
await gaw_msg.add_reaction("🎉")
db = await aiosqlite.connect("main.db")
cursor = await db.cursor()
await cursor.execute(f'SELECT * FROM storingStuff WHERE msgID = {gaw_msg.id}')
data = await cursor.fetchone()
if data is None:
await cursor.execute(f'INSERT INTO storingStuff (msgID, guildID) VALUES({gaw_msg.guild.id} , {gaw_msg.id})')
await db.commit()
await cursor.close()
await db.close()
await asyncio.sleep(timer)
new_msg = await ctx.channel.fetch_message(gaw_msg.id)
users_mention = []
for i in range(winners):
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(self.client.user))
winner = random.choice(users)
users_mention.append(winner.mention)
users.remove(winner)
displayed_winners = ",".join(users_mention)
endembed = discord.Embed(title=f"{prize}", description=f"Winner: {displayed_winners}\nHosted by: {ctx.author.mention}", color = ctx.author.color, timestamp=(datetime.datetime.utcfromtimestamp(timestamp)))
endembed.set_footer(text= 'Ended at \u200b')
await gaw_msg.edit(content = "<:done:939940228746072096> **GIVEAWAY ENDED** <:done:939940228746072096>",embed=endembed)
await ctx.send(f"Congragulations {displayed_winners}! You won the **{prize}**.\n{gaw_msg.jump_url}")
def setup(client):
client.add_cog(Start(client))
Any help with the case would be appreciated , or any code reference as I'm pretty new. Thank you for spending your time and reading this.

SQLAlchemy Class is not mapped

Im trying to update a user in FastAPI but i'm currently getting the error - Class 'api.schemas.instructor.Instructor' is not mapped
I've tried a couple of things to fix this like changing the schema and model but the results are either the error above or an error stating that the user already exists in the DB, is there anyway this can be resolved via the schema?
Heres my code;
Instructor schema
class Instructor(BaseModel):
id: str
full_name: str
phone_number: int
email: str
is_active: bool
is_superuser: bool
sex: str
car_type: str
area_covered: str
driving_school_name: str
driving_school_description: Optional[str] = None
adi_license: str
profile_image_one: Optional[str] = None
profile_image_two: Optional[str] = None
profile_image_three: Optional[str] = None
class Config:
orm_mode = True
Patch endpoint
#instructors.patch("/{user_id}")
def update(user_id: str, user: InstructorUpdate = Depends(InstructorUpdate.as_form), db: Session = Depends(d.get_db), profile_images: Optional[List[UploadFile]] = File(None)):
current_user = Instructor(**jsonable_encoder(crd.get_user(db, user_id)))
# current_user = jsonable_encoder(crd.get_user(db, user_id))
if current_user:
updated_user = crd.update_user(db, current_user, user, image_keys=image_keys)
return updated_user
else:
raise HTTPException(status_code=400, detail="User not found")
Update user function
def update_user(self, db: Session, db_obj: ModelType, usup: Any, image_keys: Optional[List[str]] = None):
obj_data = db_obj
if isinstance(usup, dict):
update_data = usup
else:
update_data = usup.dict(exclude_unset=True)
for field in obj_data:
if field in update_data:
if update_data[field] is not None:
setattr(db_obj, field, update_data[field])
# Todo - Error here "Class 'api.schemas.instructor.Instructor' is not mapped", need to fix this
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
Any help would be appreciated.

Create Object from JSON with id predefined in Grails

I have a problem! need to get a json object that already with an id already set that is not yet saved. but when trying to create the object id is null. And it is only set when call the save method generating different id's.
ex:
objetoJson = {id: "123413215123", name: "Leonan Teixeira", address: {id: "12345", city: "Victory", state: "Bahia"}}
def person = new Person (objetoJson)
end state of the object:
Person.id = null
Person.Address = null
but I need the id are stored.
the same happens if I do
person.properties = objetoJson
My classes are mapped with id 'uuid'
String id;
static mapping = {
id generator: 'uuid'
}
Solution
add a bindable:true to the constraints
class MyDomain {
static constraints = {
// allow binding of "id" attribute (e.g. in constructor or url parameters)
id bindable: true
}
}
http://www.redcube.de/assigning-id-domain-objects-grails-via-constructor/
Try this:
def jsonSlurper = new JsonSlurper()
def dataPerson = jsonSlurper.parseText('{ "id":"123456789", "nome": "Leonardo Meurer", "age":"29" }')
def person = new Person (dataPerson)

How to implement Slick + MySQL + SecureSocial?

How do I implement SecureSocial (newest snapshot version) plugin with Slick (1.0.1) and MySQL database?
I think that I have configured everything completely.
I have something like this in my User model class:
package models.auth
import securesocial.core._
import scala.slick.driver.MySQLDriver._
case class User(identityId: IdentityId,
firstName: String,
lastName: String,
fullName: String,
email: Option[String],
avatarUrl: Option[String],
authMethod: AuthenticationMethod,
oAuth1Info: Option[OAuth1Info] = None,
oAuth2Info: Option[OAuth2Info] = None,
passwordInfo: Option[PasswordInfo] = None) extends Identity
object User {
def apply(i: Identity): User = {
User(
i.identityId,
i.firstName,
i.lastName,
i.fullName,
i.email,
i.avatarUrl,
i.authMethod,
i.oAuth1Info,
i.oAuth2Info,
i.passwordInfo
)
}
}
object Users extends Table[User]("user") {
def userId = column[Long]("id", O.PrimaryKey, O.AutoInc)
def providerId = column[String]("providerId")
def email = column[Option[String]]("email")
def firstName = column[String]("firstName")
def lastName = column[String]("lastName")
def fullName = column[String]("fullName")
def avatarUrl = column[Option[String]]("avatarUrl")
def authMethod = column[AuthenticationMethod]("authMethod")
// oAuth 1
def token = column[Option[String]]("token")
def secret = column[Option[String]]("secret")
// oAuth 2
def accessToken = column[Option[String]]("accessToken")
def tokenType = column[Option[String]]("tokenType")
def expiresIn = column[Option[Int]]("expiresIn")
def refreshToken = column[Option[String]]("refreshToken")
// passwordInfo
def hasher = column[String]("hasher")
def password = column[String]("password")
def salt = column[String]("salt")
}
What do I have to do next? What imports to use and methods to implement?
Documentation is very poor.
You'll have to implement the UserService trait by extending the UserServicePlugin object.
The document is not that poor: UserService Documentation.
SecureSocial relies on an implementation of UserService to handle all the operations related to saving/finding users.

Grails. Domain class. Method AddTo*?

I have this example:
def mycreate = {
def id = params.id;
def data = JSON.parse(params.data);
def credit = Credit.get(id);
def front = new Front ();
front.properties = data;
credit.addToFronts(front).save()
render (front as JSON)
}
This action returns something like this:
{"class":"test.Front","id":null,"credits":{"class":"Credit","id":1},"dateCreated":null,"description":"write text here."}
But, for me, the params "id" and "dateCreated" are null. How can I get the values of these params?