How to customize the validation error using django Ninja? - django

```
#router.post("/addUser", response={200: responseStdr, 404: responseStdr,422: responseStdr})
def addUser(request, user: userRegister):
try:
return 200, {"status": 200,
"isError": "True",
"data": user,
"msg": "user crée avec succès",
"method": "POST"}
except :
return {"status": 201,
"isError": "True",
"data": "erreur format",
"msg": "erreur",
"method": "POST"}
```
I'm getting this error :
```
{
"detail": [
{
"loc": [
"body",
"user",
"last_name"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
```
How to send a custom message instead of this error when a field is not matching with the expected format ?

Related

How to register Swagger endpoints in Flasgger

Currently using Swagger/Flasgger/Flask to document APIs/routes in an app.
# app.py
from flask import Flask
from flasgger import Swagger
from myapp.blueprints.main import main
app = Flask(__name__)
app.register_blueprint(main)
swag = Swagger(app)
# myapp.blueprints.main.views.py
main = Blueprint('main', __name__)
#main.route('/user/<path:user_id>', methods=['GET', 'PUT', 'DELETE'])
#main.route('/user', methods=['GET', 'POST'])
def user(user_id=None):
pass
To get documentation on two routes used for the same function, I need to do two things per the Flasgger documentation:
Add a #swag_from declaration pointing to the file that contains the spec.
Give the #main.route and #swag_from the same endpoint kwarg.
When I do step 1, I start seeing the spec information in the Swagger output:
# myapp.blueprints.main.views.py
#main.route('/user/<path:user_id>', methods=['GET', 'PUT', 'DELETE'])
#main.route('/user', methods=['GET', 'POST'])
#swag_from('user_without_id.yml')
def user(user_id=None):
pass
// > curl localhost:8000/apispec_1.json
{
"definitions": {
"User": {
"properties": {
"age": {
"default": "180",
"description": "The user age (should be integer)",
"type": "integer"
},
"tags": {
"default": [
"wizard",
"hogwarts",
"dead"
],
"description": "optional list of tags",
"items": {
"type": "string"
},
"type": "array"
},
"username": {
"default": "Sirius Black",
"description": "The user name.",
"type": "string"
}
},
"required": [
"username",
"age"
]
}
},
"info": {
"description": "The test-swagger-api spec",
"termsOfService": "/tos",
"title": "test-swagger-api",
"version": "1.0"
},
"paths": {
"/user": {
"get": {
"description": "The default payload is invalid, try it, then change the age to a valid integer and try again<br/>",
"parameters": [
{
"in": "body",
"name": "body",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"200": {
"description": "A single user item",
"schema": {
"$ref": "#/definitions/User"
}
}
},
"summary": "Test validation using JsonSchema"
},
"post": {
"description": "The default payload is invalid, try it, then change the age to a valid integer and try again<br/>",
"parameters": [
{
"in": "body",
"name": "body",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"200": {
"description": "A single user item",
"schema": {
"$ref": "#/definitions/User"
}
}
},
"summary": "Test validation using JsonSchema"
}
},
"/user/{user_id}": {
"get": {
"description": "The default payload is invalid, try it, then change the age to a valid integer and try again<br/>",
"parameters": [
{
"in": "body",
"name": "body",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"200": {
"description": "A single user item",
"schema": {
"$ref": "#/definitions/User"
}
}
},
"summary": "Test validation using JsonSchema"
}
}
},
"swagger": "2.0"
}
However, as soon as I add the endpoint and methods kwargs, my output loses the spec:
# myapp.blueprints.main.views.py
#main.route('/user/<path:user_id>', methods=['GET', 'PUT', 'DELETE'])
#main.route('/user', endpoint='my-new-endpoint', methods=['GET', 'POST'])
#swag_from('user_without_id.yml', endpoint='my-new-endpoint', methods=['GET', 'POST'])
def user(user_id=None):
pass
// > curl localhost:8000/apispec_1.json
{
"definitions": {},
"info": {
"description": "The test-swagger-api spec",
"termsOfService": "/tos",
"title": "test-swagger-api",
"version": "1.0"
},
"paths": {},
"swagger": "2.0"
}
Not sure where the documentation is going. Flasgger's blueprint example doesn't show how to make this work with multiple routes on a single function.
https://stackoverflow.com/a/55109061/3316036
#swag_from needs to contain the blueprint name in its endpoint field which is unfortunately not clear from the flasgger docs.
# myapp.blueprints.main.views.py
#main.route('/user/<path:user_id>', methods=['GET', 'PUT', 'DELETE'])
#main.route('/user', endpoint='my-new-endpoint', methods=['GET', 'POST'])
#swag_from('user_without_id.yml', endpoint='main.my-new-endpoint', methods=['GET', 'POST'])
def user(user_id=None):
pass

Django and Mailgun : 552 sorry, your envelope sender domain must exist (#5.7.1)

I'm trying to send mail using Django and Mailgun through the Anymail package and with an OVH server.
I'm currently receiving the 552 sorry, your envelope sender domain must exist (#5.7.1) error.
In this question/answer, it is suggested that I would need a "from" header, but the response I'm getting seems to show that the header is already included :
"headers": {
"to": "evenements#mydomain-longversion.org",
"message-id": "20160915065953.15168.46300.4ABD80EB#mailgun.mydomain.fr",
"from": "covoiturage#mydomain.fr",
"subject": "Mail test !"
},
Here is the full response, for reference :
{
"severity": "permanent",
"tags": [],
"storage": {
"url": "https://si.api.mailgun.net/v3/domains/mailgun.mydomain.fr/messages/eyJwIjpmYWxzZSwiayI6ImI5OGIyN2QzLTM2MmEtNGJjNi05ZWViLTRlMTA0NTVmYTIxMiIsInMiOiJlNmY5NzZhZTYwIiwiYyI6InNiaWFkIn0=",
"key": "eyJwIjpmYWxzZSwiayI6ImI5OGIyN2QzLTM2MmEtNGJjNi05ZWViLTRlMTA0NTVmYTIxMiIsInMiOiJlNmY5NzZhZTYwIiwiYyI6InNiaWFkIn0="
},
"delivery-status": {
"tls": false,
"mx-host": "redirect.ovh.net",
"attempt-no": 1,
"description": null,
"session-seconds": 0.9216420650482178,
"code": 552,
"message": "552 sorry, your envelope sender domain must exist (#5.7.1)",
"certificate-verified": false
},
"recipient-domain": "mydomain-longversion.org",
"event": "failed",
"campaigns": [],
"reason": "generic",
"user-variables": {},
"flags": {
"is-routed": null,
"is-authenticated": true,
"is-system-test": false,
"is-test-mode": false
},
"log-level": "error",
"timestamp": 1473922798.282194,
"envelope": {
"transport": "smtp",
"sender": "postmaster#mailgun.mydomain.fr",
"sending-ip": "209.61.151.224",
"targets": "evenements#mydomain-longversion.org"
},
"message": {
"headers": {
"to": "evenements#mydomain-longversion.org",
"message-id": "20160915065953.15168.46300.4ABD80EB#mailgun.mydomain.fr",
"from": "covoiturage#mydomain.fr",
"subject": "Mail test !"
},
"attachments": [],
"recipients": [
"evenements#mydomain-longversion.org"
],
"size": 643
},
"recipient": "evenements#mydomain-longversion.org",
"id": "TfJKwpoZQq6bM-MW5sm6nA"
}
And here is my Django code :
def SendTestEmail(request):
if request.user.is_staff and settings.DEBUG == True :
send_mail(
subject='Mail test !',
message='''Bonjour {}, votre email a bien été envoyé.'''.format(request.user.get_full_name()),
recipient_list=['evenements#mydomain-longversion.org',],
from_email=settings.DEFAULT_FROM_EMAIL,
fail_silently=False,
)
messages.success(request, 'Email correctement envoyé !')
return redirect('rideshare_event_list')
Try using covoiturage#mailgun.mydomain.fr as your from address instead of covoiturage#mydomain.fr.
I'm afraid I'm not sure whether it's possible to use covoiturage#mydomain.fr as the from address.

Graph API Batch Request. Error (#803)

I need to get friends' albums with photos. Do that with batch query (coz https://developers.facebook.com/docs/reference/fql/).
[
{ "method":"GET",
"name":"get-friends",
"relative_url":"me/friends?fields=id,name",
"omit_response_on_success": false
},
{
"method":"GET",
"name":"get-albums",
"relative_url":"{result=get-friends:$.data.*.id}/albums",
"omit_response_on_success": false
},
{
"method":"GET",
"name":"get-photos",
"relative_url":"{result=get-albums:$.data.*.id}/photos"
}
]
But in response i got error.This is response:
[
{
"code": 200,
"body": "{
"data": [
{
"id": "xxxx",
"name": "Name Lastname"
},{
"id": "xxxx",
"name": "Name2 Lastname"
}
],
"paging": {
"next": "https://graph.facebook.com/v2.4/xxx/friends?fields=id,name&format=json&access_token=xxx&limit=25&offset=25&__after_id=enc_xxx"
},
"summary": {
"total_count": 4
}
}"
},
{
"code": 200,
"body": "{
"data": [
{
"name": "1 Photos",
"created_time": "2012-11-22T04:22:46+0000",
"id": "xxx"
},
{
"name": "2 Pictures",
"created_time": "2010-09-12T02:48:42+0000",
"id": "xxx"
},
{
"name": "3 Personal",
"created_time": "2007-10-25T15:59:06+0000",
"id": "xxx"
}
],
"paging": {
"cursors": {
"after": "NTc0NyQxMzkwOQ==",
"before": "MTAxNTuyNjIzMzQwMDg5MTA="
}
}
}"
},
{
"code": 404,
"body": "{
"error": {
"message": "(#803) Some of the aliases you requested do not exist: xxx,xxx,xxx",
"type": "OAuthException",
"code": 803
}
}"
}
]
Please tell me where is my mistake or tell me another way.
You can´t get access to albums of friends, all friend permissions have been removed with v2.0 of the Graph API: https://developers.facebook.com/docs/apps/changelog#v2_0
You can only get access to albums of users who authorized your App (with user_photos, of course).

Access meta reply message

My backed is giving me some information about the reply in a meta field. For example, when going to #/phoneNumbers/phonelocations/index a request to /api/phonelocations is sent, and this is the data received:
{
"meta": {
"api_action": "find_all",
"api_id": "phonelocations",
"content_type": "application/json",
"error_code": 200,
"errors": [
{
"admin_message": "",
"code": 200,
"message": ""
}
],
"message": "Successfully read phonelocations",
"success": true
},
"phonelocations": [
{
"_id": "0",
"city": "Berlin",
"count": 10,
"country": "DE",
"country_name": "Germany",
"loctype": "GEO",
"loctype_human": "Geographical number",
"subtype": "49GEO",
"subtype_human": "German geographical number",
"type": "phonelocation-faketype"
},
...
]
}
This is present in all replies coming from the backend. I would like to use the message in _reply_meta.message to display it to the user. Is there a standard way in Ember to access the meta information of the replies?
Just use store.metadataFor(type), in your case:
var meta = this.store.metadataFor('phonelocation');
// all metadata is in meta object
meta.message // => "Successfully read phonelocations"
See this in action http://jsfiddle.net/marciojunior/3vfQD/

Schema validation error

I have used a field 'timestamp' is of type 'datetime.datetime' used in models.py in one of the django project,
Here is data :
{"bedId": "5807a14", "description": "",
"timestamp": "2013-09-16T15:40:16.383133", "encounterId": null, "patientId": null, "type":
"end_of_shift_note", "triggeredBy": "abc"}
Here is schema :
schema =
{
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"id": "http://jsonschema.net",
"required":true,
"properties":{
"type": {
"type":"string",
"id": "http://jsonschema.net/bedNumber",
"required":true
},
"encounterId": {
"type":"string",
"id": "http://jsonschema.net/encounterId",
"required":true
},
"timestamp": {
"type" :["null","string","date-time"],
'required' :false
},
"bedId": {
"type":"string",
"id": "http://jsonschema.net/cleaningStatus",
"required":true
},
"patientId": {
"type":["string","null"],
"id": "http://jsonschema.net/facilityId",
"required":true
} ,
"id": {
"type":["string","null"],
"id": "http://jsonschema.net/id",
"required":false
},
"triggeredBy": {
"type":["string","null"],
"id": "http://jsonschema.net/lastCleanedTime",
"required":false
}
}
}
On doing schema validation : https://pypi.python.org/pypi/json-schema-validator
def assertDataMatchesSchema(self, data, schema_file_name):
with open(os.path.join("hma/resource_jsonschema", schema_file_name)) as schema_file:
try:
schema = json.load(schema_file)
validate(data, schema)
except Exception as e:
print "Schema validation Error Message :",e.message
It is giving error on terminal:
Schema validation Error Message : Expecting property name: line 19 column 5 (char 401)
Problem is simple: What would be the type format for timestamp used in above jsonschema?
Please help
Got your problem:-
You are giving type instead of format.
Following example is working for me:-
data = {"timestamp": "2013-09-16T15:40:16.21211"}
schema ="""{
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"id": "http://jsonschema.net",
"required":true,
"properties":{
"timestamp": {
"format" :"date-time",
"type":"string",
"required" :false
}
}}"""
jsonschema.validate(data,json.loads(schema))