This file runs perfectly well on its own:
import pickle
with open('model.obj', 'rb') as f:
model = pickle.load(f)
print(model)
But what I really want to do is to use model, which is a very large stored python dictionary, in my Django views.py file, like so:
from django.shortcuts import render
from modeler.load_model import model
def page(request):
return render(request, 'page.html', {'model':model})
However, when I try this, I get the error below:
File "C:\Users\mmm\PycharmProjects\MyProject\modeler\load_model.py", line 3, in <module>
with open('model.obj', 'rb') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'model.obj'
I don't understand why, because if I run the first file directly it works fine - the only extra step here is importing it into views.py (I tried including the entire load_model.py code within views.py at first, but got this error, so then tried it in this separate file and it worked on its own, so obviously the issue is that I don't know how to correctly load/import my python model objects or files within Django.
I found the answer! Apparently, all I had to do was to put the absolute path to 'model.obj' in my open statement, not just the relative path, like this:
with open('C:\\Users\\mmm\\PycharmProjects\\MyProject\\modeler\\model.obj', 'rb') as f:
model = pickle.load(f)
Related
I searched for this error, but couldn't find out how to handle it. I am getting the following error, when trying to open a file:
[Errno 36] File name too long: '/var/www/FlaskApp/FlaskApp/templates/
Here is my simple code. I am trying to open a json file and render it with Flask into a website:
#app.route("/showjson/")
def showjson():
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
data_in = open(os.path.join(SITE_ROOT, "static/data", "btc.json"), "r")
data_out = ""
for line in data_in:
data_out += line.rstrip()
data_in.close()
return render_template(data_out)
Does anybody know a solution? Many thanks in advance.
You are passing the render_template function the entirety of your JSON file, when it is looking for the filename of a template file. This is why you are getting a file name is too long error.
You can use the send_from_directory function to send the JSON file. Import the function first:
from flask import send_from_directory
Then use it like so:
#app.route("/showjson/")
def showjson(path):
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
return send_from_directory(os.path.join(SITE_ROOT, "static/data"), "btc.json")
I am writing an application that creates a midi file using the MIDIUtil library. When the user submits an HTML form, a midi file object is created with MIDIUtil. How do I allow the user to download this as a .mid file? I have tried the following code, but I end up downloading a file of 0 bytes.
return Response(myMIDIFile, mimetype='audio/midi')
I use a variant of the following code to allow my users to download images they generate. The below code should work for you. Please note that you will most likely need to specify the full server path to the file being downloaded.
from flask import send_file
download_filename = FULL_PATH_TO_YOUR_MIDI_FILE
return(send_file(filename_or_fp = download_filename,mimetype="audio/midi",as_attachment=True))
I ended up using this, and it worked.
new_file = open('test.mid', 'wb')
myMIDI.writeFile(new_file)
new_file.close()
new_file = open('test.mid', 'rb')
return send_file(new_file, mimetype='audio/midi')
Might want to just try using send_file
from flask import send_file
return send_file("yourmidifile.mid", as_attachement=True, mimetype="audio\midi")
I want to open an uploaded csv file in the clean function of a django form.
The code looks like this:
def clean(self):
file_csv = self.cleaned_data['csv_file']
records = csv.reader(open('file_csv.name, 'rU'), dialect=csv.excel_tab)
how do I get the local path of file_csv ?
Could this work ? It's using basic python though...
import os
os.path.abspath(file_csv.name)
I have a problem with opening a text file in django that is stored in my database. I want to access it via FileField of my model... the model looks something like this
class MyModel(models.Model):
saved_file = FileField()
I upload a test file via admin interface, which works ok. In my view I want to access this file. If I open it with standard python open() it works ok...
f = open(path, 'r')
a = f.readlines()
return render_to_response('base.html', {'content': a}, context_instance=RequestContext(request))
this displays lines of the file ok...
according to https://docs.djangoproject.com/en/dev/ref/models/fields/#filefield one gets a FieldFile proxy when FileField from a model is called, so
f = MyModel.objects.all().get(id=0).saved_file
should store FieldFile in f, furthermore documentation states that one opens a file from model by casting .open(mode='rb') on FieldFile, so
file = f.open(mode='rb')
should work like python .open() as stated in the documentation. So to get lines I do
file.readlines()
should return me list of lines. What happens is that I get an error saying that .readlines() atribute does not exist. I do not need the file to display it, this is just a way to test if opening a file works, but I need the file content in a variable in my view to further use it in my business logic.
Could anyone suggest a way to get the file content out of a FileField frem a model?
The documentation states that files are opened in 'rb' mode by default, but you would want to open in 'r' to treat the file as a text file:
my_object = MyModel.objects.get(pk=1)
try:
my_object.saved_file.open('r')
lines = my_object.saved_file.readlines()
finally:
my_object.saved_file.close()
Even better, you can use a context manager in Django v2.0+
my_object = MyModel.objects.get(pk=1)
with my_object.saved_file.open('r') as f:
lines = f.readlines()
Since Django 2.0 File.open does return you a file, so suggested way to work is as with context manager:
saved_file = MyModel.objects.all().get(id=0).saved_file
with saved_file.open() as f:
data = f.readlines()
Applies to old versions of Django < 2
FieldFile.open opens the file, but doesn't return anything. So in your example file is None.
You should call readlines on FieldFile. In your example it would be:
f = MyModel.objects.all().get(id=0).saved_file
try:
f.open(mode='rb')
lines = f.readlines()
finally:
f.close()
UPD: I added try/finally block, as the good practice is to always close the resource, even if exception happened.
I was trying to assign a file from my disk to the FileField, but I have this error:
AttributeError: 'str' object has no attribute 'open'
My python code:
pdfImage = FileSaver()
pdfImage.myfile.save('new', open('mytest.pdf').read())
and my models.py
class FileSaver(models.Model):
myfile = models.FileField(upload_to="files/")
class Meta:
managed=False
Thank you in advance for your help
Django uses it's own file type (with a sightly enhanced functionality). Anyway Django's file type works like a decorator, so you can simply wrap it around existing file objects to meet the needs of the Django API.
from django.core.files import File
local_file = open('mytest.pdf')
djangofile = File(local_file)
pdfImage.myfile.save('new', djangofile)
local_file.close()
You can of course decorate the file on the fly by writing the following (one line less):
pdfImage.myfile.save('new', File(local_file))
If you don't want to open the file, you can also move the file to the media folder and directly set myfile.name with the relative path to MEDIA_ROOT :
import os
os.rename('mytest.pdf', '/media/files/mytest.pdf')
pdfImage = FileSaver()
pdfImage.myfile.name = '/files/mytest.pdf'
pdfImage.save()
if you are getting error like:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position...
then you have to open the file in binary mode: open("mytest.pdf", "rb")
full example:
from django.core.files import File
pdfImage = FileSaver()
pdfImage.myfile.save('new.pdf', File(open('mytest.pdf','rb')))
If you want to upload a local file in django, you can do this
from django.core.files import File
file = open(filepath, 'rb')
file_to_upload = File(file, name=f'{your_desired_name}')
file.close()
Now you can pass the file to django rest serializer to upload or whatever your use-case is. If passing this file to serializer, be sure to close it after it has been passed to serializer.
Note: The filepath here can be django's temporary file or any stored file.