How could I produce Django REST API in XML & JSON at the same time from a same model?
I have a model and need to create 2 different outputs from that model, one in XML and one in JSON.
If you need a custom behavior for just a particular model, you can specify the renderer_classes only in the view for that model.
Assuming you have a model, let's call it Foo:
# models.py
class Foo(models.Model):
# properties
you can do this in your views.py:
from rest_framework.renderers import JSONRenderer
from rest_framework_xml.renderers import XMLRenderer
from rest_framework.views import APIView
class FooView(APIView):
renderer_classes = (JSONRenderer, XMLRenderer)
# the rest
The XMLRenderer is not anymore integral part of the Django REST Framework and has to be installed as an additional package:
$ pip install djangorestframework-xml
The offical documentation describes the use of renderers.
Related
As mentioned in the title, I attempt to
POST JSON file from C# (which is a WinForms accepting user input, then converted into a json), then to be received by python. I am quite clueless as to how to start at the C# side of the coding as I am still new to this. Would appreciate any kind help from here. Thanks
I use httpclient to communicate between the two languages, and now I would like to send the json file to the python side.
In short, the working principle of my project is:
User input parameters at WinForms that I have designed using C#, then these parameters are transferred over to Python by the flask and HTTPclient architecture.
Python process the parameters and a result is obtained, where I now wish to transfer this result back to C#, to be displayed on WinForms.
Flask is easy to use and set up for a simple POST request like this. The flask docs are excellent: https://flask.palletsprojects.com/en/2.0.x/quickstart/#a-minimal-application
Assuming you have pip installed Flask >= v2.0, a simple flask application to receive a POST request would look like:
from flask import Flask, request, jsonify
app = Flask(__name__)
#app.post('/submit_input')
def submit_input():
# check that your data is json
if request.json:
data = request.json
# do something with the data here and create a new var...
new_var = 'this is some new data'
return jsonify(message=new_var)
I am developing this project of a simple meme posting website where I take the UserName, caption, Image URL from the user and want to show all the memes on the home page of the website.
I am new to being a full stack developer, I am using FastAPI as backend and went through its documentation. So far I have been able to get the response from the HTML to the server via a Post request, but now I want to store the data in some database and send that data back to the Home page of the website. I tried finding tutorial videos but wasn't able to get the ones which could help me.
Any kind of help is appreciated.
Below is some code about how I am performing the current requests.
from fastapi import Request, status, BackgroundTasks
from fastapi.responses import JSONResponse
from tutorial import app,templates
import time
from datetime import datetime
from pydantic import BaseModel
from typing import Optional
class Record(BaseModel):
name:str
caption:str
meme_type: Optional[str] = None
img_meme:str
#app.post("/")
async def create_record(record: Record):
background_tasks.add_task(_run_task,record)
return record
def _run_task(name: str,caption: str,meme_type:str,img_meme: str):
time.sleep(3)
with open("memes.txt",mode="a") as file:
now=datetime.now()
content=f""" "Name":{name} \nCaption:{caption} \nURL:{img_meme} : now}\n"""
file.write(content)
FastAPI documentation has all the answers you need.
I want to store the data in some database
SQL Databases - You can use any relational database you want. The documentation has example codes using SQLAlchemy.
Async SQL Databases - You can connect to your relational databases using async/await using a third-party package called databases.
NoSQL Databases - FastAPI can also be integrated with any NoSQL. The documentation has example codes using Couchbase.
send that data back to the Home page of the website
HTMLResponse - If your app is simple and straightforward.
Templates - If you need template rendering. The documentation has example codes for Jinja2.
I'm trying to implement tests for the Django Rest Framework.
Most of my tests pass and setting them up went smooth, but i'm having an issue now where an assertEqual never succeeds because it keeps comparing JSON with an OrderedDict.
I have no idea where the OrderedDict comes from since DRF should only return JSON (right?).
Might it be possible that the testing environment is parsing the JSON before comparison? That would suck.
I'm doing an integrated test that only tests the data in the response of a GET request to a certain resource, I do this based on JSON fixtures. I'm not testing a specific component of the REST framework since my implementations of the components are so simple they're already tested by the tests in the DRF project.
Anyways, I hope someone can help me!
As explained here, this is because the default format for requests during tests is multipart instead of json. You can specify the format by providing it to your api call like so:
response = self.client.get('/something/1', format='json')
Or you can set the default test request format in your settings.py like so:
REST_FRAMEWORK = {
'TEST_REQUEST_DEFAULT_FORMAT': 'json', # Use application/json instead of multipart/form-data requests in tests.
}
To fix it for all your tests automagically.
It sounds like you're using response.data (which returns the parsed json objects) instead of response.content (which gives the raw json string).
See http://www.django-rest-framework.org/api-guide/testing/#testing-responses
If your tests look something like this:
class SomeTests(APITestCase):
def test_something(self):
response = self.client.get('/something/1')
# assertions with response
Then response will certainly be an OrderedDict rather than a JSON document. Luckily Django 1.9 has introduced the response.json() method (https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.Response.json) so you can easily convert the response into JSON. Note that you could also use python's json library.
The catch here is that Django's test client (that DRF extends) is a "dummy browser" (https://docs.djangoproject.com/en/1.9/topics/testing/tools/#the-test-client) and doesn't work exactly like an in-browser framework such as Selenium would. Thus, HTTP calls are actually just simulated HTTP calls that focus on testing your logic and that correct routing/views/serializers/etc. are being used.
You can dump your data into json format :
import json
return HttpResponse(json.dumps(data))
I solved the problem by using SerializerMethodField.
Simply, within the serializer class copy next last 3 lines and replace result with the json member that cause the problem
class ConfigSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Config
fields = ('id', 'url', 'email', "result",)
# COPY NEXT 3 LINES AND CHANGE 'result' WITH THE JSON MEMBER THAT CAUSE THE PROBLEM
result = serializers.SerializerMethodField()
def get_result(self, obj):
return obj.result
Before the result shows as:
{result: "OrderedDict([('key1', 1), ('key2', OrderedDict([('key3', [1, 2, 3])]))])"}
After solution, result become:
{"result": {"key1":1,"key2":{"key3":[1,2,3]}}}
I have stored some simple data in the GAE datastore. Now I'd like to pull it out, but I'd like to do so with the results as JSON. Is there a simple way to do this?
You can first convert your datastore model to a dictionary and then use simplejson (python 2.5) or json (python 2.7) package to convert the dictionary to json. Typically this is how the last line of your handler will look like:
self.response.out.write(simplejson.dumps(some_datastore_entity.to_dict()))
The new ndb interface to the datastore provides a to_dict method by default. You can check it out here
class Handler(webapp2.RequestHandler):
def get(self):
<do your GQLQuery here>
self.response.headers['Content-Type'] = 'application/json'
self.response.body = json.dumps(<your data in dict or dict list>)
self.response.set_status(200)
In Grails I have a model class User that has a one-to-one mapping with another model class Address. When returning a user in JSON format from my controller I never see the address class, just the id. In my User class I have:
class User {
Address address
...
static mapping = {
...
address fetch: 'join'
...
}
And then in my controller I do
User user = user.get(1)
render user as JSON
Is there a way to change the mapping to make the 'as JSON' pull back the address class?
I am running on Grails 1.3.7.
There are Two types of JSON Converters i.e:
grails.converters.deep.JSON
grails.converters.JSON
.
.
What you need is a Deep Converter,
Just change the Imported Class To:
// Dont Use: import grails.converters.JSON
import grails.converters.deep.JSON
Note: Grails 1.3.7 import grails.converters.deep.JSON is fiine, in Grails 2.0 its deprecated.
The Difference Between these two is, that the "Deep" one will also JSONify the nested Classes, Whereas Standard Converter will not.
Hope that help
Regards
Kushal
Have you tried setting your converter to be deep?
JSON.use("deep"){
User user = user.get(1)
render user as JSON
}
There is a bit of stuff around the Custom Object Marshallers that you can dig into here, but my first try would be to just try the deep conversion.