I want to change response header of
> from django.http import JsonResponse
function for example change Date header
how?
You can alter it as a key-value dictionary, so:
from django.http import JsonResponse
response = JsonResponse()
response['Date'] = 'some value'
return response
Related
import json
import requests
def get_quote():
response = requests.get(
"http://kitkabackend.eastus.cloudapp.azure.com:5010/highscore/crowns/list?Country=GB&start=0&count=1")
json_data = json.loads(response.text)
quote = str(json_data["scores"][0]["User"]["Crowns"])
return (quote)
quote = get_quote()
print(quote)
Why is this giving me JSON decoder error and how do i fix this?
I am quite new to django. I am trying to convert sql data fetched from a remote postgresql database into JSON so as to use it in react. But while dumping the data it throws as error.
`AttributeError: 'str' object has no attribute 'get'`
I tried many versions of dumping sql data into json like coneverting data into list and using RealDictCursor but each one of them throws a new error.
Views.py
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.http import HttpResponse
from .marketer import marketer
def marketer_list(request):
return JsonResponse(marketer)
marketer.py (function to fetch data and establish the connection)
from django.shortcuts import render, get_object_or_404
import json
import psycopg2
from psycopg2.extras import RealDictCursor
def marketer(self):
connection = psycopg2.connect(user = "db-user",
password = "*****",
host = "18.23.42.2",
port = "5432",
database = "db-name")
cursor = connection.cursor(cursor_factory = RealDictCursor)
postgreSQL_select_Query = "select id from auth_permission"
result = cursor.execute(postgreSQL_select_Query)
#print("Selecting rows from mobile table using cursor.fetchall")
#mobile = dictfetchall(result)
#items = [dict(zip([key[0] for key in cursor.description], row)) for
row in result]
return json.dumps(cursor.fetchall(), indent=2)
Error at Url page
AttributeError: 'str' object has no attribute 'get'
or
in some other methods
is not JSON serializable
I am trying to save data in form of JSON (returned as result from POST request)
def get_data(...):
...
try:
_r = requests.post(
_url_list,
headers=_headers
)
return _r.json()
except Exception as ee:
print('Could not get data: {}'.format(ee))
return None
Into a table in SQLITE database as backend.
def add_to_flight_data(_data):
if _data:
try:
new_record = FlightData(data=_data)
db.session.add(new_record)
db.session.commit()
print('Data instertedto DB!')
return "Success"
except Exception as e:
print('Data NOT instertedto DB! {}'.format(e))
pass
This is my simple flask code
import os
import time
import auth
import json
import requests
import datetime
from flask import Flask
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy
# from safrs.safrs_types import JSONType
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir, "2w.sqlite"))
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
db = SQLAlchemy(app)
ma = Marshmallow(app)
class FlightData(db.Model):
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.DateTime, server_default=db.func.now())
json_data = db.Column(db.JSONType, default={})
def __init__(self, data):
self.data = data
It seems like there is perhaps no option to save JSON in sqlite
json_data = db.Column(db.JSONType, default={})
Please ADVISE
Thanks.
I believe that you should be using db.JSON, not db.JSONType as there is no such column type in sqlalchemy.
Regardless of that, SQLite has no JSON data type, so sqlalchemy won't be able to map columns of type db.JSON onto anything. According to the documentation only Postgres and some MySQL are supported. There is support for JSON in SQLite with the JSON1 extension, but sqlalchemy will not be able to make use of it.
Your best bet then is to declare the column as db.Text and use json.dumps() to jsonify the data on write. Alternatively modify your get_data() function to check for a JSON response (check the Content-type header or try calling _r.json() and catching exceptions), and then return _r.content which will already be a JSON string.
Use json.loads() to read data back from the db.
This question already has answers here:
Return JSON response from Flask view
(15 answers)
Closed 5 years ago.
I know I can set the status code of a response with Response(status=200). How can I return JSON data while setting the status code?
from flask import Flask, Response
#app.route('/login', methods=['POST'])
def login():
response = Response(status=200)
# need to set JSON like {'username': 'febin'}
return response
Use flask.jsonify(). This method takes any serializable data type. For example I have used a dictionary data in the following example.
from flask import jsonify
#app.route('/login', methods=['POST'])
def login():
data = {'name': 'nabin khadka'}
return jsonify(data)
To return a status code, return a tuple of the response and code:
return jsonify(data), 200
Note that 200 is the default status code, so it's not necessary to specify that code.
UPDATE
As of Flask 1.1, the return statement will automatically jsonify a dictionary in the first return value. You can return the data directly:
return data
You can also return it with a status code:
return data, 200
You can append the data to the response like this:
from flask import Flask, json
#app.route('/login', methods=['POST'])
def login():
data = {"some_key":"some_value"} # Your data in JSON-serializable type
response = app.response_class(response=json.dumps(data),
status=200,
mimetype='application/json')
return response
The response data content type is defined by mimetype parameter.
I want to return only JSON data for this view method and I'm not sure if I'm doing it the right way. Any tips would be greatly appreciated.
def helpful_click(request,object):
if request.POST and request.is_ajax():
form = HelpfulForm(request.POST)
if form.is_valid():
form.save()
return simplejson.dumps({'helpful':True})
My understanding is that every Django view should return an HttpResponse object, and you should also make sure the mime-type is set correctly:
http://jibbering.com/blog/?p=514
In a project I was working on I had something like this:
return HttpResponse(simplejson.dumps({'helpful':True}), 'application/json')
There is a JsonResponse object:
>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'