FastAPI: where to set exclude_unset=True? - patch

I am learning fastAPI and don't know how to update user info partially. The given solution is to set exclude_unset=True, but I don't know where to write it. Here are my pieces of code:
routers/user.py:
#router.patch('/{id}', status_code=status.HTTP_202_ACCEPTED)
def update_user(id, request: sUser, db: Session = Depends(get_db)):
user = db.query(mUser).filter(mUser.id == id)
if not user.first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'The User with the id {id} is not found')
user.update(request.dict(exclude={'createdAt'}, exclude_unset=True))
db.commit()
return user.first()
PS exclude = {'createdAt'} works, but exclude_unset=True doesn't..
Here is my user schema:
schemas.py
class User(BaseModel):
username: str
dob: datetime.date
password: str
createdAt: datetime.datetime

that's because you are using it on a User model instance.
If you want to receive partial updates, it's very useful to use the parameter exclude_unset in Pydantic's model's .dict().
so use it on Pydantic object.
more info in documentation: https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict

Set it as follows:
a.dict(exclude_unset=True)
where a is the object, see the example here:
https://github.com/samuelcolvin/pydantic/issues/1399

Related

Unable to get results from related documents in FastAPI-Users and Beanie

I have a couple of models:
class Message(Document):
phone: str
message_body: str
user: Indexed(PydanticObjectId)
class Settings:
name = "Message"
class User(BeanieBaseUser[PydanticObjectId]):
messages: Optional[List[Link[Message]]]
They have a relationship using Beanie Link.
The Message model is a custom Model and User is the default of FastAPI-Users.
When I save a record with insert() on a Message that is the child model, it does not establish a relationship with the parent. Returning the dict with null messages field.
Any idea what could be the error?
One way to do this is with fetch_link
#app.get("/messages")
async def list_messages(user: User = Depends(current_active_user)):
await user.fetch_link(User.messages)
return user.messages
Checkout the response from FastAPI-Users creator
https://github.com/fastapi-users/fastapi-users/discussions/1006#discussion-4101669

how to store a value from database to a global variable and use it everywhere we need it

I don't know if this is the way to ask this, also I want to achieve this without state management.
so here's the code that getting user is from firebase
final docUsers = FirebaseFirestore.instance.collection('users').doc();
final userObject = Users(
id: docUsers.id,
name: userName,
email: emailAdress,
password: password,
);
await docUsers.set(userObject.toJson());
userID = docUsers.id;
userID = docUsers.id; the user id is the global variable here, so I assigned the value to the global variable when the id received. but when it using its shows the value is null, how to achieve this without statemanagement (I meant bloc, provider and like many others. not the "state management").
so how can I achieve that?
Could you show how and when your value is NULL?
But this might help:
class MyGlobalVariables {
static String userId = '123';
}
MyGlobalVariables.userId = 'abc';
print( MyGlobalVariables.userId ); // = abc
It looks like you want to create entries for new users of your App in the database. If this is the case, one would want to use Firebase Authentication for dealing with that:
https://firebase.google.com/docs/auth/

How to use Realm with SwiftUI forms

Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
All changes to a managed object (addition, modification and deletion) must be done within a write transaction. For example,
// Update an object with a transaction
try! realm.write {
author.name = "Thomas Pynchon"
}
I can make a Realm sub-class conform to ObservableObject. However, I don't see how to make the realm properties updatable in SwiftUI. Realm property example below.
#objc dynamic var myName: String = "Adam"
Realm automagically sets up the schema based on #objc dynamic var. I don't see a way to get #Published on a realm property. SwiftUI will render a TextField, but crashes when the value is edited.
TextField("Quantity (\(shoppingItem.myUnit!.myName))", value: $shoppingItem.stdQty, formatter: basicFormat)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.numbersAndPunctuation)
Is there any way to wrap SwiftUI state changes inside a Realm write transaction?
Another way to do this is to use a Custom Binding, and when setting the property, open a transaction and save data to realm.
TextField("Quantity (\(shoppingItem.myUnit!.myName))",
value: Binding(get: {shoppingItem.stdQty},
set: {(value) in
//if your state property is in a view model, all this code could be like viewModel.saveData(newMessage: value)
let realm = try! Realm()
try! realm.write {
shoppingItem.stdQty = value
}
}),
formatter: basicFormat)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.numbersAndPunctuation)
This will save to realm on every character inserted
Consider the Realm property, stdQty shown below. It can only be changed within a write transaction.
import RealmSwift
import Combine
class ShoppingItems: Object, ObservableObject
let objectWillChange = PassthroughSubject<Void, Never>()
#objc dynamic var stdQty: Double = 1
You cannot bind stdQty without the error in the original question. However you can create a calculated variable that can be bound.
var formQty: Double {
get {
return stdQty
}
set {
objectWillChange.send()
if let sr = self.realm {
try! sr.write {
stdQty = newValue
}
}
}
}
Binding the calculated variable works fine.
TextField("Quantity (\(shoppingItem.myUnit!.myName))", value: $shoppingItem.formQty, formatter: basicFormat)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.numbersAndPunctuation)
Answer limitation: objectWillChange is only triggered by the calculated variable. Changes in the form are reflected in the form. Changes in the realm don't trigger a Combine objectWillChange yet.

How to perform multiple Http requests (Tasks) in bulk in Elm lang

I want to load user profile before rendering something into the page but the whole user profile is composed of different parts that are loaded by multiple HTTP requests.
So far I'm loading user profile in sequence (one by one)
type alias CompanyInfo =
{ name: String
, address: ...
, phone: String
, ...
}
type alias UserProfile =
{ userName: String
, companyInfo: CompanyInfo
, ...
}
Cmd.batch
[ loadUserName userId LoadUserNameFail LoadUserNameSuccess
, loadCompanyInfo userId LoadCompanyInfoFail LoadCompanyInfoSuccess
...
]
But that's not very effective. Is there a simple way how to perform a bunch of Http requests and return just one complete value?
Something like this
init =
(initialModel, loadUserProfile userId LoadUserProfileFail LoadUserProfileSuccess)
....
You can achieve this using Task.map2:
Edit: Updated to Elm 0.18
Task.attempt LoadUserProfile <|
Task.map2 (\userName companyInfo -> { userName = userName, companyInfo = companyInfo })
(Http.get userNameGetUrl userDecoder |> Http.toTask)
(Http.get companyInfoGetUrl companyInfoDecoder |> Http.toTask)
You can then get rid of the individual LoadUserName... and LoadCompanyInfo... Msgs. In Elm 0.18, the need for separate Fail and Succeed Msgs is addressed by Task.attempt expecting a Result Error Msg type, so that LoadUserProfile is defined like this:
type Msg
= ...
| LoadUserProfile (Result Http.Error UserProfile)
map2 will only succeed once both tasks succeed. It will fail if any of the tasks fail.

Protractor + CucumberJS MySQL Query

Currently my automation framework uses protractor from cucumberJS. We use chai as promised as a assertion library, and I have recently come across a need to do direct mysql queries against a database.
How would I structure a step-definition to be able to get a query, and use the query results within the same step? My current struggles are the asynchronous way protractor is being run, causing me to perform the query after the step requiring the query results happens, and also the scope of which to pass the JSON Object that is created as a result of the query.
this.loginWithMysqlUser = function(uname) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : '*******',
password : '*******',
database : '*******'
});
connection.connect();
connection.query('SELECT * FROM prot_users WHERE username = ?', [uname], function(err, rows) {
if(err) throw err;
mysqlUser = {
username: rows[0].username,
password: rows[0].password
};
});
connection.end();
loginpage.login(mysqlUser);
};
This function resides on loginpage declaration.
So typically your cucumber test script would like:
Feature: As an admin I would like to check if a customer has an
account
Scenario: Check that customer name is registered in DB
Given that I am logged in as admin
And I wish to check that customer (foo) is registered
Then I expect following details from DB query:
| username | password | database |
| foo | bar | mysql |
with step definitions for:
Given(/^that I am logged in as admin$/, function(callback){
..
logic goes here
..
});
And(/^I wish to check that customer (foo) is registered$/,
function(username, callback){
// create connection with db as described
// with supplied username
// Use a promise to create mySQL connection
// and queries DB based on username as described
// on successful resolution set DBResult to results
// for username, password and database
// on error set DBResult to undefined
});
Then(/^I expect following details from DB query$/, function(data,
callback)
{
var rows = data.raw;
// extract values of input table cells into DBExpect using
// rows[0].username
// rows[0].password
// rows[0].database
// Check equality of DBResult and DBExpect objects
..
expect.isFulfilled(DBResult).toEqual(DBExpect).notify(callback);
});
I ended up containing all of the logic for the login and functions that needed to work with the data within the connection.query function.
Seemed to work ok, and protractor was able to be called from within that query function.

Resources