Django version of flask.jsonify jsonify - json

I am currently trying to migrate a project from flask over to Django as practice and just to get it working on Django... I was wondering if there is a method within Django that performs the job of flask.jsonify?
If not, how else would you recommend I can emulate the same functionality?

from django.http import JsonResponse
def someView(request):
...
return JsonResponse(someDictionary)

Related

POST JSON generated from C# to be received by Python

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)

Flask TypeError: Object of type Decimal is not JSON serializable

We are using flask for our application service. Internally we are using Jsonify to return the response and our response contains decimal data.
Couple of things to mention here.
We are using Windows machine
Some of my colleagues they are not getting any issue with the data with same configuration.
One thing we observed is flask by default uses simplejson if installed. If not, then it will
fall back to json package.
Sample data : jsonify({'response':Decimal('12345.00000')})
Our question is why for some people flask by default using simplejson and for others it's not able to identify simplejson(even though installed) and using only json throwing decimal json error.
Any idea what might be the root cause and what change needs to be done, let flask know to use simplejson over json ?
For time being we did below manual change in flask package.
Instead of jsonify({'response': Decimal('12345.00000')}) can't you just use jsonify({'response': float('12345.00000')})?
is there any chance you're using different versions of flask?
https://github.com/pallets/flask/issues/3555
in version 2, support was dropped for simplejson, but as noted in the comments, you can make it use simplejson for the JSONEncoder:
from simplejson import JSONEncoder
app.json_encoder = JSONEncoder
it also looks as though there is a fix for the decimal issue that was PR'ed but is not yet released, and will be released in version 2.0.2

How to connect FastAPI to frontend HTML

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.

Prevent Flask from Displaying '.html' in URL

I'm working on a project, using Flask. Apart from the index page, all other pages have '.html' extension displayed at the end of their URL (for example 127.0.0.1:5000/mypage.html), which is normal. For some reasons, i do not want the extension displayed, i prefer the URL displays with the extension (like this 127.0.0.1:5000/mypage. Here's what i have:
Flask
#app.route('/mypage', methods=['POST', 'GET'])
def mypage():
return render_template('/mypage.html')
HTML
Mypage</li>
I'll appreciate any help with this.
Following the documentation: Creating URLs in Flask, you can do this like this, and you are pretty much good to go.
Please Note: Do not use / inside the render_template
#app.route('/mypage', methods=['POST', 'GET'])
def index():
return render_template('mypage.html')
If you want to hardcode the url, you can use url_for(). But as the documentation says:
Flask can generate URLs using the url_for() function of the flask package. Hardcoding URLs in the templates and view functions is a bad practice.
HTML
Mypage</li>

Django REST API in XML & JSON

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.