Send JSON data with render_template() in Flask [duplicate] - flask

This question already has answers here:
JavaScript raises SyntaxError with data rendered in Jinja template
(3 answers)
Closed 6 months ago.
I need some clarification.
I want to load a JSON file in a route and return it's data with the render_template function. I am new to working with JSON in Flask and wanted to know if this is possible?
#app.route("/")
def hello_world():
script_dir = os.path.dirname(__file__) #<-- 1. # Access and open JSON file.
rel_path = "roles.json"
abs_file_path = os.path.join(script_dir, rel_path)
with open(abs_file_path) as f:
data = json.load(f)
return render_template('page.html', data=data) <----2. Want to send the JSON data with the template.
Then I want to then use this JSON data javascript inside the page.html Can this be done? Is there a better way?
The tutorials I have seen have had JSON data retrieved by a fetch request on page load or sent by creating a separate rout and returning just the JSON.

You're using the "with" keyword wrong,
The data variable is only known in the "with" scope,
try this :
#app.route("/")
def hello_world():
script_dir = os.path.dirname(__file__)
rel_path = "roles.json"
abs_file_path = os.path.join(script_dir, rel_path)
currentFile = open(abs_file_path)
data = json.load(currentFile)
currentFile.close()
return render_template('page.html', data=data)

Related

Retrieve data in Python Flask app send by Vue app - Can't read it as JSON [duplicate]

This question already has answers here:
Are global variables thread-safe in Flask? How do I share data between requests?
(4 answers)
Store large data or a service connection per Flask session
(1 answer)
Closed 4 months ago.
I'm new to both Flask and Vue.js and I'm a bit confused with everything.
So far, I've created a Flask app that sends data to Vue app, a table with filtering options.
I now want to do the opposite, send filtered data from Vue and store them in a python object.
Here is my simplified code :
app.py
app = Flask(__name__)
app.config.from_object(__name__)
CORS(app, resources={r"/*":{'origins':"*"}})
# Sending data to http://localhost:5000/prices
#app.route("/prices", methods=["GET","POST"])
def all_prices():
dt_items = init_data()
json_items = prepare_data_for_front(dt_items)
return jsonify({"items" : json_items})
# Retrieve data from http://localhost:8085/saved
#app.route("/saved", methods=["GET", "POST"])
def all_select():
dt_saved = request.values
return jsonify(dt_saved)
app.run()
Script in PricesComponent.vue
import axios from 'axios';
export default {
...
methods: {
async postItems() {
await axios.post("http://localhost:5000/saved", JSON.stringify(this.filteredTable))
.then(response => {
console.log(response.data);
})
.catch(err=>{
console.log(err);
});
},
...
}
However, when I got to http://localhost:5000/saved, this is empty. There is no error.
Looking at the console.log, I can see that response.data is an object and not a json, maybe the problem is that my flask app can't jsonify it.

In django, how can i upload file via url?

Hi i'm making my own webserver using django.
i just want to upload local file to django server.
i google every method but i can't get answer.
every method using form or html but i don't want to using form and html
example : from www.localfolder/example.txt to /media/examplefolder.
i don't know how to do.. any help?
this is my code.
#csrf_exempt
def download_file(request, file):
fl_path = 'media/'
filename = str(file)
fl = open(fl_path, 'r')
mime_type, _ = mimetypes.guess_type(fl_path)
response = HttpResponse(fl, content_type=mime_type)
response['Content-Disposition'] = "attachment; filename = %s" % filename
return response
What did you search for when you googled? These were the top 2 results for Django files
https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/
https://docs.djangoproject.com/en/3.0/topics/files/
Seems to have everything you are looking for.

Get data from JsonResponse in django

I wanted to know how to get data from a JsonResponse in django. I made a JsonResponse that works like this
def pfmdetail(rsid):
snpid = parseSet(rsid)
if not snpid:
return HttpResponse(status=404)
try:
data = SnpsPfm.objects.values('start', 'strand', 'type', 'scoreref', 'scorealt',
rsid=F('snpid__rsid'), pfm_name=F('pfmid__name')).filter(snpid=snpid[0])
except SnpsPfm.DoesNotExist:
return HttpResponse(status=404)
serializer = SnpsPfmSerializer(data, many=True)
return JsonResponse(serializer.data, safe=False)
and then I call directly the method like this
def pfmTable(qset,detail):
source = pfmdetail(detail)
print(source)
df = pd.read_json(source)
but it gives me an error. I know it's wrong because with the print it returns the status of the response which is 200 so I suppose that the response is fine but how can I access the data inside the response? I tried import json to do json.load but with no success. I even tried the methods of QueryDict but stil I can't acess to the content I'm interested
P.S. I know that data contains something because if i display the jsonresponse on the browser i can see the JSON
As you can see here: https://docs.djangoproject.com/en/2.2/ref/request-response/#jsonresponse-objects.
JsonResponse object holds json in its content attribute.
So to access it try this:
df = pd.read_json(source.content)
Or to see it printed do:
print(source.content)
If you aren't using pandas, then you should process the content attribute of the JSONResponse object like this:
r = json.loads(source.decode())
I got the answer here: How to parse binary string to dict ?

How to read JSON data return by the Facebook access_token

I'm trying to get the facebook username of a logged in user in my site. I have this code in my view (on Django) :
code = request.GET.get('code')
url = 'https://graph.facebook.com/oauth/access_token?client_id=%(id)s&redirect_uri=http://127.0.0.1:8000/skempi/home&client_secret=%(secret)s&code=%(code)s'%{'id':fb_id,'secret':fb_s,'code':code}
response = urllib2.urlopen(url)
html = response.read()
dic = dict(urlparse.parse_qsl(html))
graph_url = 'https://graph.facebook.com/me?access_token='+dic.get('access_token')
when I do return HttpResponseRedirect(graph_url) I can see the JSON data. However, I'm not able to read that data using
import simplejson
d = simplejson.load(graph_url)
context ={'user':d}
return render_to_response('home.html', context, context_instance=RequestContext(request))
I get this error :
'str' object has no attribute 'read'
You have to actually download the JSON before simplejson can decode it.
response = urllib2.urlopen(graph_url)
data = simplejson.load(response)

Deserializing JSON in Django

This one has had me pulling out my hair. I've been trying to deserialize JSON in Django for the last couple hours.
I have a function:
# in index.html
function updateWidgetData(){
var items=[];
for statement here:
for statement here:
var item={
id: $j(this).attr('id'),
collapsed: collapsed,
order : i,
column: columnId
};
items.push(item);
var sortorder={ items: items};
$j.post('2', 'data='+$j.toJSON(sortorder), function(response)
{
if(response=="success")
$j("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000);
setTimeout(function(){
$j('#console').fadeOut(1000);
}, 2000);
});
}
And I'm trying to deserialize the JSON in django:
# in views.py
if request.is_ajax():
for item in serializers.deserialize("json", request.content):
item = MyObject(id=id, collapsed=collapsed, order=order, column=column)
return HttpResponse("success")
else:
....
And it hasn't been working. I know this is probably a really trivial question, but I've never used JSON before, and I'd really appreciate some help. Thanks!
serializers.deserialize is for deserializing a particular type of JSON - that is, data that was serialized from model instances using serializers.serialize. For your data, you just want the standard simplejson module.
And the second thing wrong is that your response isn't just JSON - it is an HTTP POST with JSON in the data field. So:
from django.utils import simplejson
data = simplejson.loads(request.POST['data'])
from django.core import serializers
obj_generator = serializers.json.Deserializer(request.POST['data'])
for obj in obj_generator:
obj.save()
Objects should now be saved and visible in django admin