upload image to folder using python - python

I want to browse image & upload it to folder using python. I have tried a variety of solutions posted on on the forum but none of them worked in my case. Please guide me on what needs to be corrected. Thanks all for your quick help.
I'm getting error
raise AttributeError(attr)
AttributeError: has_key
#!/usr/bin/env python
import cgi, os
import cgitb; cgitb.enable()
import cgi
import datetime
import webapp2
import cgi, os
import cgitb; cgitb.enable()
from google.appengine.ext import ndb
from google.appengine.api import users
guestbook_key = ndb.Key('Guestbook', 'default_guestbook')
class Greeting(ndb.Model):
author = ndb.UserProperty()
content = ndb.TextProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
greetings = ndb.gql('SELECT * '
'FROM Greeting '
'WHERE ANCESTOR IS :1 '
'ORDER BY date DESC LIMIT 10',
guestbook_key)
for greeting in greetings:
if greeting.author:
self.response.out.write('<b>%s</b> wrote:' % greeting.author.nickname())
else:
self.response.out.write('An anonymous person wrote:')
self.response.out.write('<blockquote>%s</blockquote>' %
cgi.escape(greeting.content))
self.response.out.write("""
<form enctype="multipart/form-data" action="/sign" method="post">
<p>File: <input type="file" name="file1"></p>
<p><input type="submit" value="Upload"></p>
</form>
</html>""")
class Guestbook(webapp2.RequestHandler):
def post(self):
form = cgi.FieldStorage()
# A nested FieldStorage instance holds the file
#file = models.FileField(upload_to='documents/', max_length=5234,blank=True, null=True,)
# docfile = forms.FileField(label='', show_hidden_initial='none',required=True,)
fileitem = str(self.request.get('file1'))
# Test if the file was uploaded
if self.request.has_key('file1'):
# strip leading path from file name to avoid directory traversal attacks
fn = os.path.basename(fileitem.file)
open('files/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
app = webapp2.WSGIApplication([
('/', MainPage),
('/sign', Guestbook)
], debug=True)

You need to stop here and go back and read the introductory documentation on appengine and the python runtime. If you read through the intro docs you will see the section on the python runtime and the sandbox and it's restrictions.
On examining that section of documentation you will see you can not write to the filesystem in appengine. It is also worth noting the other restrictions whilst you are at it.
As to where in the code your error is, you should at least include a stacktrace and look at the particular lines of code where the error occurs and then ask specific questions about that rather than dump all of your code and saying what error you got.
At the moment I don't see a lot of point looking at the problem in your code where the has_key error occurs, that error is self explanatory and the rest of what you are trying to do just won't work anyway.

Your GAE Python project files are read only. You can only change those files when you update your project using appcfg.py or push-to-deploy.
But you can use Google cloudstorage folders or subdirectories to upload, write or overwrite files.
Docs: https://developers.google.com/appengine/docs/python/googlecloudstorageclient/
If you use the appid default bucket for your folders, you have 5 GB of free quota.

Related

Python cx_Freeze Exe Blogger API authentification issue - blogger.dat and secrets in root directory but posting doesnt work - no errors

I just created a python executable with cx_freeze, there are multiple blog API's like tumblr and all in all it worked out well.
But Google's Blogger API doesnt work. I get the secrets from ouath2 and put them into the directory. Then I start my .exe file and want to work with a google blog, it redirects me to an URL where it asks me to accept access on my blogger data. Until now everything is okay, now it should create a blogger.dat file in the directory with expire token etc.
But it doesnt do anything, it tells me authentification succesfull but doesnt create the blogger.dat file. If you manualy put it in there. it recognizes it, because there is no redirect, but it doesnt post my content and no errors aswell.
thats the directory which I created with cx_Freeze: no blogger.dat is created there even if the authentification is succesfull, putting it in there manualy make google recognize it, but i cannot post
http://puu.sh/k2VK1/109e3cd348.png
Thats the class that I use for authetification: I also tryed to replace doc with "blogger.dat"
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
from oauth2client import client
from googleapiclient import sample_tools
# Authenticate and construct service.
def google_blogger_zugangsdaten():
global service
service, flags = sample_tools.init(
sys.argv, 'blogger', 'v3', __doc__ , "client_secrets.json",
scope='https://www.googleapis.com/auth/blogger')
def google_blogger_execute(google_blogname, bild_uri_zum_posten, alt_attribut_bild, title_attribut_bild, google_post_title, google_post_content):
blogs = service.blogs()
thisusersblogs = blogs.listByUser(userId='self').execute()
for blog in thisusersblogs['items']:
print('The blog named \'%s\' is at: %s id is: %s' % (blog['name'], blog['url'], blog['id']))
posts = service.posts()
#blog_id = 0
#google_blogname = "Development Blog"
for blog in thisusersblogs['items']:
if blog['name'] == google_blogname:
#blog_id = blog['id']
request = posts.insert(blogId=blog['id'], body = {"title" : google_post_title, "content" : "<img src='" + bild_uri_zum_posten + "' title='" + title_attribut_bild + "' alt='" + alt_attribut_bild + "'><br>" + google_post_content})
request.execute()
Thank you all, my first post here, usualy I only find solutions here. Hope I dont missed something

Just getting started on Google App Engine and being greeted with a blank page

I'm currently in Udacity's CS253 (Web Development) course, and I'm getting through the second homework project (the ROT13) website. I paid attention to the lecture and I think I have a good grip on the code in the file naisho.py, which is here:
import webapp2
import codecs
import cgi
form = """
<form method="post">
Tell me a secret...
<br>
<input type="text" name="secret" value="%(secret)s">
<div style="color: red">%(error)s</div>
<br>
<br>
<input type="submit">
</form>
"""
class MainPage(webapp2.RequestHandler):
def process(s):
return codecs.encode(s, "rot_13")
def escape(s):
return cgi.escape(s, quote = True)
def write_form(self, error="", secret=""):
self.response.out.write(form % {"error": error,
"secret": escape(secret)})
def get(self):
#self.response.headers['Content-Type'] = 'text/plain'
self.write_form()
#self.response.headers['Content-Type'] = 'text/plain'
#self.response.write(self.request)
def post(self):
self.redirect('/thanks')
class ThanksHandler(webapp2.RequestHandler):
def get(self):
n = process(secret)
self.response.out.write(n)
def escape(s):
return cgi.escape(s, quote = True)
application = webapp2.WSGIApplication([
('/', MainPage), ('/thanks', ThanksHandler)], debug=True)
and file app.yaml provided:
application: naisho
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: naisho.application
I navigate to the folder in the terminal (I use OSX 10.9.3), enter dev_appserver.py --port=9999 . to load localhost:9999, but get a blank page when I load it into my browser. I am absolutely puzzled as to why. Could someone point me in the right direction and also possibly point me in the direction of a reference to better diagnose these sorts of things? Thank you folks kindly in advance.
First, your code contains some bugs and indentation problems.
The bugs is that escape and process are methods of the class, so they should contain self as their first argument and be called as self.escape or self.process. An alternative would be to move those methods out of the class as functions.
Once you do that, in the console you shouldn't see any error hidden in Stack Traces except for an annoying 303 error.
For whatever reason, I also get those 303 errors when running on the dev server, but if you deploy it to an App Engine instance, it works smoothly.
You could try to deploy to the App Engine first, and look into their logs to catch your bugs/indentation as it makes it easier to spot them.

Changing the root directory Python and mod_wsgi

I started using Mako templates engine on my localhost. However, everytime I want to select template, I need to enter full location of template (ex. c:/Users/username/Desktop/xampp/htdocs/blog/scripts/templates/index.html'). I want to change it, for example to enter just 'scripts/templates/index.html' or similar each time.
Any suggestions how to do that?
Use mako's TemplateLookup class. For your example, using the sample in the documentation:
from mako.template import Template
from mako.lookup import TemplateLookup
template_path = "c:/Users/username/Desktop/xampp/htdocs/blog"
mylookup = TemplateLookup(directories=[path])
def serve_template(templatename, **kwargs):
templatename = "scripts/templates/index.html"
mytemplate = mylookup.get_template(templatename)
print mytemplate.render(**kwargs)

How to run a Python script in a web page

I'm very new to Python. I just know what Python is.
I have created the below code (in Python IDLE):
print "Hi Welcome to Python test page\n";
print "Now it will show a calculation";
print "30+2=";
print 30+2;
Then I saved this page in my localhost as index.py
I run the script using
http://localhost/index.py
But it does not show the executed Python script. Instead, it showed the above code as HTML. Where is the problem? How can I run a Python file in a web page?
In order for your code to show, you need several things:
Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.
Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.
Setting this up can be quite the hassle, so be prepared.
As others have pointed out, there are many web frameworks for Python.
But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:
Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.
Add these 2 lines in the beginning of the file:
#!/usr/bin/python
print('Content-type: text/html\r\n\r')
After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.
Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.
Using the Flask library in Python, you can achieve that.
Remember to store your HTML page to a folder named "templates" inside where you are running your Python script.
So your folder would look like
templates (folder which would contain your HTML file)
your Python script
This is a small example of your Python script. This simply checks for plagiarism.
from flask import Flask
from flask import request
from flask import render_template
import stringComparison
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template("my-form.html") # This should be the name of your HTML file
#app.route('/', methods=['POST'])
def my_form_post():
text1 = request.form['text1']
text2 = request.form['text2']
plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
if plagiarismPercent > 50 :
return "<h1>Plagiarism Detected !</h1>"
else :
return "<h1>No Plagiarism Detected !</h1>"
if __name__ == '__main__':
app.run()
This a small template of HTML file that is used:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter the texts to be compared</h1>
<form action="." method="POST">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="submit" name="my-form" value="Check !">
</form>
</body>
</html>
This is a small little way through which you can achieve a simple task of comparing two strings and which can be easily changed to suit your requirements.
If you are using your own computer, install a software called XAMPP (or WAMP either works). This is basically a website server that only runs on your computer. Then, once it is installed, go to the xampp folder and double click the htdocs folder. Now you
need to create an HTML file (I'm going to call it runpython.html). (Remember to move the Python file to htdocs as well.)
Add in this to your HTML body (and inputs as necessary).
<form action = "file_name.py" method = "POST">
<input type = "submit" value = "Run the Program!!!">
</form>
Now, in the Python file, we are basically going to be printing out HTML code.
# We will need a comment here depending on your server. It is basically telling the server where your python.exe is in order to interpret the language. The server is too lazy to do it itself.
import cgitb
import cgi
cgitb.enable() # This will show any errors on your webpage
inputs = cgi.FieldStorage() # REMEMBER: We do not have inputs, simply a button to run the program. In order to get inputs, give each one a name and call it by inputs['insert_name']
print "Content-type: text/html" # We are using HTML, so we need to tell the server
print # Just do it because it is in the tutorial :P
print "<title> MyPythonWebpage </title>"
print "Whatever you would like to print goes here, preferably in between tags to make it look nice"
Well, the OP didn't say server or client side, so I will just leave this here in case someone like me is looking for client side:
Skulpt is a implementation of Python to run at client side. Very interesting, no plugin required, just simple JavaScript code.
With your current requirement, this would work:
def start_html():
return '<html>'
def end_html():
return '</html>'
def print_html(text):
text = str(text)
text = text.replace('\n', '<br>')
return '<p>' + str(text) + '</p>'
if __name__ == '__main__':
webpage_data = start_html()
webpage_data += print_html("Hi Welcome to Python test page\n")
webpage_data += fd.write(print_html("Now it will show a calculation"))
webpage_data += print_html("30+2=")
webpage_data += print_html(30+2)
webpage_data += end_html()
with open('index.html', 'w') as fd: fd.write(webpage_data)
Open the index.html file, and you will see what you want.

HTML forms not working with python

I've created a HTML page with forms, which takes a name and password and passes it to a Python Script which is supposed to print the persons name with a welcome message. However, after i POST the values, i'm just getting the Python code displayed in the browser and not the welcome message. I have stored the html file and python file in the cgi-bin folder under Apache 2.2. If i just run a simple hello world python script in the browser, the "Hello World" message is being displayed. I'm using WinXP, Python 2.5, Apache 2.2. the code that i'm trying to run is the following:
#!c:\python25\python.exe
import cgi
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
reshtml = """Content-Type: text/html\n
<html>
<head><title>Security Precaution</title></head>
<body>
"""
print reshtml
User = form['UserName'].value
Pass = form['PassWord'].value
if User == 'Gold' and Pass == 'finger':
print '<big><big>Welcome'
print 'mr. Goldfinger !</big></big><br>'
print '<br>'
else:
print 'Sorry, incorrect user name or password'
print '</body>'
print '</html>'
The answer to it might be very obvious, but its completely escaping me. I'm very new to Python so any help would be greatly appreciated.
Thanks.
This
i'm just getting the Python code
displayed in the browser
sounds like CGI handling with Apache and Python is not configured correctly.
You can narrow the test case by passing UserName and PassWord as GET parameters:
http://example.com/cgi-bin/my-script.py?UserName=Foo&PassWord=bar
What happens if you do this?
You may have to extract the field values like this
User = form.getfirst('UserName')
Pass = form.getfirst('PassWord')
I know, it's strange.

Categories

Resources