Uploading a file Google App - Python - python

Hoping someone can help cure my stupidity. I am creating a webapp where I need to upload csv files and process them. I am struggling to get my code to work in its simplest form. I can get the page to load up but as soon as I press the submit button to post the file I get a 403 Forbidden Error: Access was denied to this resource.
When I run it in the google app interactive console it does not give me any errors. Can some one point me in the right direction please.
HTML:
{% extends base_layout %}
{% block header_title %}
{% trans %}Upload Documents{% endtrans %}
{% endblock %}
{% block content %}
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<br>
<input type="submit" name="submit" value="Submit">
{% endblock %}
Handler class:
class Upload(BaseHandler):
def get(self):
return self.render_template('upload.html')
def post(self):
file = self.request.POST.getall('myfile')
#file will be process with data going into models here.
self.response.out.write("success")

You cannot simply upload a file to app engine since the file system is read only. You have to upload to either cloud storage or blob storage. When using either you have to use the facilities for each.
The easiest and fastest way to upload files via a form is with the blobstore api.

Related

Unable to change Django default templates

I'm learning Django using W. Vincent's "Django for beginners". I got to the part where we have to customize the password change page (p. 186). According to the author:
"Django already has created the views and URLs for us, we only need to
change the templates."
I created a new template password_change_form.html but when I start a local server and go to the localhost/accounts/password_change, I still see the old default page with the "Django Administration" header. Here is the code:
{% extends "base.html" %}
{% block title %}Password Change{% endblock title %}
{% block content %}
<h1>Password change</h1>
<p>Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly.</p>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input class="btn btn-success" type="submit" value="Change my password">
</form>
{% endblock content %}
I'm surprised because everything worked well up until this point, as I was able to successfully updated the login and signup pages' templates. What do you think might be going wrong? Thanks.
This is happening because in "Django For Beginners" book, the author does not configure static file setting in the settings.py file the css you are seeing in the template is because of bootstrap's cdn.
If you want to clear that problem you have to configure static files settings in settings.py.
This article by the same author can be helpful for you

how to encrypt a file before uploading in django

Im building a project secure file sharing.which encrypts a file before uploading into local computer and decrypts while downloading if the user has the decryption key.I was stuck how to encrypt a file before uploading into my pc
I'm following this approach which is mentioned below.
https://ruddra.com/documentation-of-django-encrypt-file/#basic-usage
but i dont't know how to link with my code. can anyone help me
views.py
def upload(request):
context={}
if request.method == 'POST':
upload_file= request.FILES["document"]
fs=FileSystemStorage()
name=fs.save(upload_file.name, upload_file)
context['url'] = fs.url(name)
return render(request, 'accounts/upload.html',context)
upload.html
{% include 'accounts/main.html'%}
<pre>
Upload your files for sharing
</pre>
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="document">
<button type="submit">Upload</button>
</form>
{% if url %}
<p> Uploaded file:{{ url }}</p>
{% endif %}
{% endblock %}
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL= '/media/'
To encrypt a file BEFORE uploading to the server, it means you need to encrypt it within the browser - e.g. using JavaScript. Here's a thread that can help you to encrypt stuff in JS:
JavaScript AES encryption and decryption (Advanced Encryption Standard)
If you're feeling up to the challenge, look into running AES in WASM to speed up encryption (important for large files).
Note that in Django, all python code is executed ON THE SERVER. The linked example in the question shows how to encrypt files on the server AFTER uploading them:
https://ruddra.com/documentation-of-django-encrypt-file/#basic-usage
Note that encrypting the file on the browser before uploading is only a small portion of the whole problem. To have a secure file sharing service, you would probably want to have a way to share the key with the other users who need to decrypt it. For that you'd probably need to use asymmetric encryption, e.g., wrap (encrypt) the key using other users' public keys before uploading it.

How to run python file within flask?

In my flask application I have a so called 'about' page, from this about page i want to run this python script.
This is the script:
https://github.com/stakeinlinkies/sendwithasmile/blob/master/sendsmile.py and it has 2 dependency xml files.
this is the content of my about page:
{% extends "layout.html"%}
{% block content%}
<h1>about</h1>
<button type="button" class="btn btn-success" >Start A.I.</button>
{% endblock content %}
When I run the program in the command line the prgramm turns on the webcam and a video window pops up and than detects for a smile.
I want to run this on the website so i want the video window to be rendered on my about page.
How can i achieve this.
You'll have to import sendsmile.py file into you main flask app file:
import sendsmile
...
#app.route('/sendsmile', methods=['POST', 'GET'])
def sendsmile():
sendsmile() #run sendsmile
return('', 200)
HTML
{% extends "layout.html"%}
{% block content%}
<h1>about</h1>
<iframe name="iframe1" src="#"></iframe>
Start A.I.
{% endblock content %}

Opening csv file in Python using Flask

So, I am trying to open an .csv file in Python using Flask. I copies the code from the Python library, but I go from one error message to the other and I don't know what I am doing wrong. The latest error code I get on the below code is: TypeError: invalid file:
Any ideas what I am doing wrong?
My Python code/Flash route is as follows:
#app.route("/admin", methods=["GET", "POST"])
#login_required
def admin():
"""Configure Admin Screen"""
# if user reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# load csv file with portfolio data
with open(request.files["portfolios"]) as csvfile:
portfolios = csv.DictReader(csvfile)
# load csv file in dictionary
for row in portfolios:
print(row['first_name'], row['last_name'])
else:
return render_template("admin.html")
My html/Flask code is:
{% extends "layout.html" %}
{% block title %}
Admin
{% endblock %}
{% block main %}
<h2>Admin Console</h2>
<h3> Upload Portfolio Data</h2>
<form action="{{ url_for('admin') }}" method="post" enctype=multipart/form-data>
<fieldset>
<label class="control-label">Select Portfolio Upload File</label>
<input id="input-1" type="file" class="file" name="portfolios">
<h3>Upload Security Lists</h2>
<label class="control-label">Select Security Upload File</label>
<input id="input-1" type="file" class="file" name="securities">
<div class="form-group">
<button class="btn btn-default" type="submit" value = "upload">Upload</button>
</div>
</fieldset>
</form>
{% endblock %}
The file is already open. open takes a string filename and created an open file object, but you don't need to do that because objects in request.files are already open file-like objects.
portfolios = csv.DictReader(request.files['portfolios'])

Django Development Server, blank HttpResponse on Post Method

I am developing an application in Django using Heroku's tools and guides for doing so, and have ran into an issue. On my local dev environment I cannot get a response from my views if it I use the post method. Currently i'm using a simple form to post a collection of ids to a view.
def webinarToHS(request):
errors = []
if request.method == 'GET':
webinars = get_upcoming_webinars()
return render_to_response('webinarToHS.html', {'webinars': webinars.json(), 'length': len(webinars.json())/2}, RequestContext(request))
elif request.method == 'POST':
method = request.method
return HttpResponse("test")
In the console it comes back with a 200 response ok. However the browser displays a blank html page (empty body tags).
On the production/heroku server, i get back a response, so I don't believe there is an issue with the code itself but rather with my settings file. I went back through the heroku django setup guide and used an environment variable on my local machine to switch those settings off if i'm in local dev but I am still having this issue.
Can anyone give me a clue as to where to start looking for a fix? I'm running windows 7 with a virtualenv wrapper, python 2.7.5 and django 1.5
Thanks.
As per requested in the comments, the WebinarToHS template file is as below:
<html>
<head>
<title>Add Webinars to Hubspot</title>
<style>
html, body {background-color: #eee;}
#wrapper {background-color: #fefefe; width:60%; margin:0 auto; position:relative; margin-top:50px; padding:25px;}
form {text-align:center;}
label {font-weight:bold;}
.submit {float:right;}
.check {float:left; text-align:left; max-width:48%; margin-right:2%;}
</style>
</head>
<body>
<div id="wrapper">
<form name="form" action="{%url 'G2WApi.views.webinarToHS' %}" method="post">
{% csrf_token %}
<label for="webinarKey">Choose the Webinar(s) you would like to add to hubspot:</label><br/><br/>
<div class="check">
{% for webinar in webinars %}
<input type="checkbox" name="webinars[]" value="{{ webinar.webinarKey }}" />{{ webinar.subject }}<br/>
{% if forloop.counter|divisibleby:length %}
</div><div class="check">
{% endif %}
{% endfor %}
</div>
<div style="clear:both; height:10px;"></div>
<input class="submit" type="submit" value="Add to Hubspot" />
</form>
</div>
</body>
</html>
Although it doesn't actually solve the question at hand, I found a way that was much better for what I was trying to do. I discovered that everything in my code for the POST Method worked except the output or rendering of a template. HttpRedirection worked, and also the Django Messages System. I found a tutorial on how to use that and it works perfectly for posting responses back to the originating template.
The Django Messaging system, for those who aren't aware, is a way to add details back to the originating request object. Here's a snipper
messages.success(request, "success message")
return HttpResponseRedirect(request.path)
The first line of code is attaching the message to the request object (in this case the same one that was passed in to the view) and then in the second line of code we are just redirecting back to the requesting path. Django handles all the rest you just have to add some code to your template like follows:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
to loop through and display your messages however you wish. I hope this helps someone.

Categories

Resources