Serving a downloadable file in django throws server error - python

I am new to django. I am trying to serve downloadable files using django FileWrapper. But, I keep getting internal server error messages.
EDIT: My settings.py
DEBUG=True
link in html:
abcd.com/downloadResult/fileName/
My urls.py
url(r'^downloadResult/(\w{0,50})/$',"myApp.views.showResult",name="Result"),
My views.py
from django.core.servers.basehttp import FileWrapper
def showResult(request,fileName):
file=open("/path/to/file/"+fileName+".txt","r")
response=HttpResponse(FileWrapper(file),mimetype='application/force-download')
response['Content-Disposition']='attachment; filename=%s' % smart_str(fileName+".txt")
file.close()
return response
Can someone please direct me to some discussions or point out what I am missing?
Thanks!

I figured out the problem with my code. I closed the file before I return anything. After commenting out the second last line in views.py, it works fine. I found the error message in apache log file but did not get any error message in the browser even though DEBUG was set to True.
Now, the problem with this solution is that, there are files that are opened but never closed.

Related

Python Dash Plotly: dcc.Upload gives error POST 500 after deployment

I used dcc.upload() to handle the file upload. The file can be uploaded and read locally on the localhost.
But after the deployment, I received POST 500 internal server error. And the message received is:
{message: "Callback error updating output-data-upload.children", html: "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final/…ded or there is an error in the application.</p>\n"}
The code related to this error message has been attached below as a screenshot, where output-data-upload is the id of a html.Div() component.
And the upload-data is the id of the dcc.Upload() component.
In the parse_contents(), I'm trying to filter for xls or xlsx files only. in the update_output(), I'm trying to display the name of the uploaded file.
I've looked up the 500 error code and have tried to change some permission settings but nothing really worked out.\
I really appreciate the help!
code related

Python: Request POST method is not uploading a fie to the web server

I am stuck with this problem that I have had for a while.
I have code here that is intended to upload a file to a web server.
class uploadFile_Functions():
def __init__(self, DESTINATION_URL, TARGET_FILE):
self.DESTINATION_URL = DESTINATION_URL
self.TARGET_FILE = TARGET_FILE
def uploadFile_WebServ(self):
dest_site = self.DESTINATION_URL
t_file = self.TARGET_FILE
with open(t_file,'rb') as f:
print('Uploading the file to the server')
upload_req = requests.post(dest_site, files={t_file:f})
print('Upload successful')
The dest_site will contain the link to the webpage folder that I have, and the t_file will contain the file to be uploaded.
What happens is that when I run this code, there were no errors thrown during runtime, and the shell printed the 'Upload successful' statement. But I checked the webpage folder in chrome, and the file is not even there.
I do not know if this needs some sort of authentication since this is a web server. I was able to get a file from the same webpage folder using the GET method, but no success so far with the POST method.
I appreciate any answer that I get from you guys. Thank you!

No www Prefix Returns Django 404

When I go to www.keithirwin.us, my site works fine. But when I go to keithirwin.us without the prefix, I get a django 404 error ("Page not found at /").
Now since I get a django error and not my browser's "server not found" error, it must at least be pointing to my server. But the django error says "You're seeing this page because debug = True" and that's false! So who's django project is it?
This problem has really twisted my brain. I'm just about ready to call an exorcist.
Aha! The DEBUG = True was from mezzanine's local_settings.py. I still don't know why I'm getting a 404 but I can figure it out from here.

Display a specific template when Django raises an exception

In my django app, I have multiple places where I raise a specific custom exception DeserializationError. My goal is to show/redirect to a pretty page to show the user this error, including the error message, when this error is raised. Basically, a page that says something like
Something went wrong. Please contact webmaster#email.com.
Error: DeserializationError. Message: SomeModel, "somemodel", does not exist.
Would this even be possible? I've been trying to search for a solution but haven't been able to find anything yet.
Most likely such errors will return HTTP 500 server error.
In django you can write your own custom view to handle such cases and return your own page with the html that you like.
The 500 (server error) view explains writing server error views. There are more types of errors handled as explained on same page.
An option for handling HTTP 500 errors, add this to your Settings file,
handler500 = 'mysite.views.my_custom_error_view'
and in the view, you can render the "error page" using
HttpResponseNotFound('<h1>Page not found</h1>')
the server_error() view will be overridden by handler500.

appengine improperly configured database error when trying to send mail (using django_bootstrap)

I am using django_bootstrap.py there are similar errors but i could not find solution to it. I am using django helper(please do not suggest non-rel)
What i was trying to do was, inside a static html js website attaching a feature of sending mail, through a contact form. The form would take the data, and jQuery would validate and make a POST AJAX request to the url "/sendmail/" the views.py i have the following code:
def sendmail(request):
logging.info("here1")
msg = request.POST['comment']; sub = request.POST['subject']
name = request.POST['name']; frm = request.POST['email']
sender = name + " " + frm
logging.info(sender)
a = mail.send_mail(sender=sender,
to="to#example.com",
subject=sub,
body=msg)
logging.info(request)
logging.info(a)
return http.HttpResponse("1")
I get absolutely no error when i remove the line:
a = mail.send_mail(sender=sender,
to="to#example.com",
subject=sub,
body=msg)
However with that line being there, i get the following error:
<class 'django.core.exceptions.ImproperlyConfigured'>: You haven't set the DATABASE_ENGINE setting yet.
I look at my settings.py file and try making some changes:
1 adding two lines as done in django-nonrel settings.py
DATABASES['native'] = DATABASES['default']
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}
This gave a 500 error on server and the page did not open.
2 I tried putting
DATABASE_ENGINE = 'dummy'
This works locally but doesnot work on server(appspot).
3 I tried putting
DATABASE_ENGINE = 'appengine'
This too gives a 500 error.
Please let me know how to solve it.
This looks messed up in all sorts of ways. Don't use bootstrap.py, it looks outdated as it's trying to load django 0.96. GAE now supports django 1.3.
Please don't use the django helper. It's not being maintained or supported by anyone. If you have problems with it, the solution is to upgrade to nonrel.
I recommend installing django-nonrel properly. Keep in mind django-nonrel is a full replacement of django. Most of it's the same, but some parts are modified to work with appengine backends. You cannot take pieces of django-nonrel and expect it to work with normal django, without a fair bit of hackery. The DATABASES lines in the settings file will only work with django-nonrel.
http://www.allbuttonspressed.com/projects/djangoappengine
Django helper doesn't have an email backend that uses appengine's email API. That's available in Django-nonrel's djangoappengine package.
If you are not using a database in your application, you can set DATABASES = {} in your settings.py file. This will fix the problem "You haven't set the DATABASE_ENGINE setting yet".

Categories