python the hard way ex 50: "permission denied" - python

Per the book, I successfully installed lpthw.web, then created the module named app.py. First I typed it exactly, then tried cutting and pasting from the website, to be 100% sure.
When I run app.py on my OS Yosemite Mac, I get the message
Permission denied.
I think it has to do with the command import web. I tested this by commenting out all of the lines except this one and I got the same error. However, I made a simple file, put it in bin and was able to run it. Not sure what’s going on. How do I change this?
Thanks for your help.
For reference, here is the code for bin/app.py:
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "hello world"
return greeting
if __name__ == "__main__":
app.run()

Related

UnsupportedOperation: not writable

from flask import Flask
app = Flask(__name__)
#app.route("/")
def function():
return "Hello Work"
print('here')
if __name__ == "__main__":
app.run(debug=True)
The print works, but the server does not start.
I found the answer here, courtesy of josechval. This worked for me. https://github.com/plotly/dash/issues/257
Jose says: "You need to edit the "echo" function definition at ../site-packages/click/utils.py . The default value for the "file" parameter must be sys.stdout instead of None. Do the same for the "secho" function definition at ../site-packages/click/termui.py"
You need to check if __name__ == '__main__' and not if name == 'main'.
Resolved the issue
There is a change that I made in the configuration file "Utils"
I commented a this part:
if message:
write("Something Something")
I dont know the exact reason why is this happening, but yeah it surely worked for me.
My problem solved adding these two lines:
app.css.config.serve_locally = True
app.script.config.serve_locally = True
I should say that I had done both suggestions (changing echo and secho file and downgrading my flask to 0.12.2 but they had not been working for me)

Get the list of all environment names of Elastic beanstalk using Python

I am using below python code to get the ApplicationName and EnvironmentName of the AWS Elastic Beanstalk. Can anyone please let me know how to print/get all the environment names by using for loop or some other way. Thanks
#!/usr/bin/env python3
import boto3
import json
def get_info():
try:
eb = boto3.client('elasticbeanstalk',"us-east-1")
response = eb.describe_environments()
app_name=(response['Environments'][0]['ApplicationName'])
env_name=(response['Environments'][0]['EnvironmentName'])
print app_name
print env_name
except:
raise
if __name__ == '__main__':
get_info()
I am not sure about the code, as I have no way to test it presently, however, assuming that response['Environments'] is a list, the following should work. Please note that, if it is not a list then it will not work or you may have to change the code a bit to get the right result.
#!/usr/bin/env python3
import boto3
import json
def get_info():
try:
eb = boto3.client('elasticbeanstalk',"us-east-1")
response = eb.describe_environments()
for item in response['Environments']:
app_name = response['Environments'][item]['ApplicationName']
env_name = response['Environments'][item]['EnvironmentName']
print app_name
print env_name
except:
raise
if __name__ == '__main__':
get_info()
Also, given the fact that you are using a try-except block, I will say that it is always wiser to catch the particular exception you want to catch. I am not sure which that will be, but a all-catch except is generally not a good idea.
Thanks #SRC; I made below changes to your script to get it working for me.
app_name = item['ApplicationName']
env_name = item['EnvironmentName']

File is not created/opened when using with open

I am using Flask and testing some code in Python. I am trying to store in a log file a Flask request and a string every time a post is done.
This is my code:
from flask import Flask, render_template, request
from vsearch import search4letters
app = Flask(__name__)
def log_request(request, results: str) -> None:
print(request)
with open('vsearch.log', 'a') as log:
print(request, results, file=log)
#app.route('/search4', methods=['POST'])
def do_search() -> 'html':
phrase = request.form['phrase']
letters = request.form['letters']
title = 'Here are your results:'
results = str(search4letters(phrase, letters))
log_request(request, results)
return render_template('results.html',
the_phrase=phrase,
the_letters=letters,
the_title=title,
the_results=results,
)
#app.route('/')
#app.route('/entry')
def entry_page() -> 'html':
return render_template('entry.html',
the_title='Welcome to search4letters on the web!')
if __name__ == '__main__':
app.run(debug=True)
This is my HTML view:
After pressing Do it!, 'vsearch.log' should contained what I have printed to it, but it does not. In addition, when the file does not exists, it does not get created.
I have tried changing the mode of open to 'a+', but I get the same results. I have also made a debug, and these lines are just executed with no errors raised.
Could somebody explain me what is going on, and how can I solve this problem ?
Since you're using Flask it's much better to use the built in logging functionality. See: http://flask.pocoo.org/docs/0.12/errorhandling/#logging-to-a-file
So, for example, on app startup you'd have:
import logging
file_handler = logging.FileHandler('/path/to/your/flask.log')
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
Then wherever you want to log something in your application you'd log to warning or above, or whatever you set the file handler log level to:
#app.route('/whatever')
def whatever():
app.logger.warning('Whatever!')
return render_template('whatever.html')
Thanks to #AlexHall, I have been able to solve this problem. The solution is to specify the full absolute path to the file.
def log_request(request, results: str) -> None:
with open('/absolute/path/to/the/file/vsearch.log', 'a') as log:
print(request, results, file=log)
In addition, following #AlexHall suggestion to know the current working directory. I have seen that this is:
/Applications/PyCharm.app/Contents/bin
so when not specifying the full absolute path the file 'vsearch.log' was created here.
EDIT:
So, it seems that the problem was I was running my code from PyCharm. However, when I use the terminal and I just run:
$ python webapp.py
I do not need to specify the full absolute path.
EDIT:
I was able to solve this issue, and I probably screwed up the settings at some point, but after deleting all the run configurations in PyCharm, and running the program from webapp.py everything has been solved.
I really want to thank #AlexHall since he gave me all tips to solve this problem.

Not Found Error (404) with Static files when running from prompt

I recently moved from windows to raspberry pi for my app. It loaded at least once but now for the life of me I can't get static files to load again.
If I run the python script from shell as sudo (or without) I get 404 for all static files, dynamic links still work as expected.
If I run it from IDLE logging in as 'pi' it works fine.
Relevant code:
from bottle import route, run, get, request, static_file
#get('/pumps')
def pumpData():
return json.dumps(pump.getPumps())
# root dir
#route('/<filename>')
def server_static(filename):
return static_file(filename, root='')
# css dir
#route('/css/<filename>')
def server_static(filename):
return static_file(filename, root='css')
run(host='myip', port=2000, debug=True)
What could be causing the issue? I could guess its something to do with permissions but I dont know how I would fix it.
I don't think it's a permission problem. (That would return a 403.) It's most likely a path issue.
The good news is: fixing it should be straightforward. (Famous last words. ;) You should either
specify absolute an path as the root param to static_file, or
call os.chdir() into the static file root before you call bottle.run.
So, this:
return static_file(filename, root='/path/to/your/static/file/root')
or this:
os.chdir('/path/to/your/static/file/root')
run(host='myip', port=2000, debug=True)

Dynamically loading Python application code from database under Google App Engine

I need to store python code in a database and load it in some kind of bootstrap.py application for execution. I cannot use filesystem because I'm using GAE, so this is my only choice.
However I'm not a python experienced user.
I already was able to load 1 line of code and run it using eval, however a piece of code with two lines or more gave me a "invalid syntax" error.
I'm also thinking if it's possible to extend the "import" loader to implement the DB loading.
Thanks!
I was able to do what I intent after reading more about Python dynamic code loading.
Here is the sample code. I removed headers to be lighter:
Thanks anyway!
=============
class DynCode(db.Model):
name = db.StringProperty()
code = db.TextProperty(default=None)
=============
class MainHandler(webapp.RequestHandler):
def get(self):
dyn = DynCode()
dyn = "index"
dyn.code = """
from google.appengine.ext import webapp
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("Hello World\\n")
self.response.out.write("Hello World 2\\n")
"""
dyn.put()
self.response.out.write("OK.")
def main():
application = webapp.WSGIApplication([('/update', MainHandler)], debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
==================================
def main():
query = DynCode.all()
dyncodes = query.fetch(1)
module = imp.new_module('mymodule')
for dyn in dyncodes:
exec dyn.code in module.__dict__
application = webapp.WSGIApplication([('/', module.MainHandler)], debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
=======================
If you want a more robust mechanism, you probably want to read PEP302, which describes input hooks. You can use these to import code rather than having to eval it.
I somewhat agree with the commentators above, it sounds kind of dangerous. However:
I experimented a little with App Engine Console ( http://con.appspot.com/console/ ), and eval() indeed tended to throw SyntaxError's.
Instead, the exec statement might be your friend ( http://docs.python.org/release/2.5.2/ref/exec.html ).
I managed to run this in App Engine Console:
>>> exec "def f(x):\n x = x + 1\n y = 10\n return x + y"
>>> f(10)
21
So try the exec statement, but remember the many, many (many!) perils of code coming directly from end-users.

Categories

Resources