Validating model URL type using ORMAR - fastapi

I have a model, Users
class Users(ormar.Model):
class Meta(BaseMeta):
tablename = "users"
id: int = ormar.Integer(primary_key=True)
first_name: str = ormar.String(max_length=255)
middle_name: Union[str, None] = ormar.String(nullable=True, max_length=255)
last_name: Union[str, None] = ormar.String(nullable=True, max_length=255)
i wish to add a url profile_image and I want the URL validation to be done at database level instead of API level
Is it possbile to do the same? without switching to SQLAlchemy?
I have tried lookup the docs, but could not find anything helpful.

Related

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/

FastAPI: where to set exclude_unset=True?

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

How do I suppress CosmosDB "default" info in resultsets?

I want to suppress the CosmosDB information in the following resultset, how can that be done?
{
"id": null,
"_rid": null,
"_self": null,
"_ts": 0,
"_etag": null,
"topLevelCategory": "Shorts,Skirt"
},
This is an extract of course but I dont want to show the ID etc as they serve no purpose in this result but I cannot figure out how to suppress that info.
I expect the following
{
"topLevelCategory": "Shorts,Skirt"
},
Query looks as follows
$"SELECT DISTINCT locales.categories[0] AS topLevelCategory " +
$"FROM c JOIN locales in c.locales " +
$"WHERE locales.country = '{apiInputObject.Locale}' " +
$"AND locales.language = '{apiInputObject.Language}'";
Interesting thing is if I cast the result as a JOBJECT I dont get the system data, I only get it if I createDOcumentQuery as DOcument, so a workaround would be as follows
IQueryable<JObject> queryResultSet = client.CreateDocumentQuery<JObject>(UriFactory.CreateDocumentCollectionUri(databaseName, databaseCollection), parsedQueryObject.SqlStatement, queryOptions);
but that has other async issues but the above does not show the system generate IDs but the below one does
var query = client.CreateDocumentQuery<Document>(UriFactory.CreateDocumentCollectionUri(databaseName, databaseCollection), parsedQueryObject.SqlStatement, queryOptions).AsDocumentQuery();
var result = await query.ExecuteNextAsync<Document>();
These are system-generated properties of items in Cosmos DB.
Surely,you could filter them in the sql: select c.topLevelCategory from c, don't mention them or use select * from c. Filtering in sql is the best method, better than secondary processing of result set.
Update Answer:
Your situation is executing the exact same query the JOBJECT does not show the system data but the Document does.
My explanation as below:
Document Class is a self-contained base class of Document DB .NET package.It has these generate properties:
SDK will try to map the result data one by one to the entity class which you defined in the CreateDocumentQuery<T>.
So actually,you already find the solution.You could define your custom pojo to receive the result data. Just contain the properties you want in that pojo inside like:
class Pojo : Document
{
public string id { get; set; }
public string name { get; set; }
}
That would have both business implications and no more redundant fields.Hope i'm clear on this.

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.

In MVC app using JQGrid - how to set user data in the controller action

How do you set the userdata in the controller action. The way I'm doing it is breaking my grid. I'm trying a simple test with no luck. Here's my code which does not work. Thanks.
var dataJson = new
{
total =
page = 1,
records = 10000,
userdata = "{test1:thefield}",
rows = (from e in equipment
select new
{
id = e.equip_id,
cell = new string[] {
e.type_desc,
e.make_descr,
e.model_descr,
e.equip_year,
e.work_loc,
e.insp_due_dt,
e.registered_by,
e.managed_by
}
}).ToArray()
};
return Json(dataJson);
I don't think you have to convert it to an Array. I've used jqGrid and i just let the Json function serialize the object. I'm not certain that would cause a problem, but it's unnecessary at the very least.
Also, your user data would evaluate to a string (because you are sending it as a string). Try sending it as an anonymous object. ie:
userdata = new { test1 = "thefield" },
You need a value for total and a comma between that and page. (I'm guessing that's a typo. I don't think that would compile as is.)
EDIT:
Also, i would recommend adding the option "jsonReader: { repeatitems: false }" to your javascript. This will allow you to send your collection in the "rows" field without converting it to the "{id: ID, cell: [ data_row_as_array ] }" syntax. You can set the property "key = true" in your colModel to indicate which field is the ID. It makes it a lot simpler to pass data to the grid.

Resources