Putting python code online- confusion with my app.py script - python

So I'm getting into the process of putting some of my first python code online and I'm a little fuzzy about some things. When we assign app to web.application(urls, globals()), what is going on exactly? Also, the line form = web.input(name="Nobody", greet=None) is referring to the two input forms in my other script called hello_form, but what is its purpose here? We're calling form.greet and form.name on the next line I see, but those should be variables created based on user input, (yet we say name = "Nobody"?).
import web
urls = (
'/hello', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/', base="layout")
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="Nobody", greet=None)
greeting = "%s, %s" % (form.greet, form.name)
return render.index(greeting = greeting)
if __name__ == "__main__":
app.run()

app = web.application(urls, globals())
creates a variable named app and stores the result of calling web.application() in it. In other words, you create a web application object, and store that object in app.
form = web.input(name="Nobody", greet=None)
The values specified for name and greet here are the default values - namely, those used if no user specified values are provided in the request.

Related

How to have separate routers module in Flask?

How can I decouple this class? I would like to put the paths in another file, is it possible to move the routes in another file?
#api.route('/home', '/api/email')
class Server(Resource):
def create_server(app, oauth=None):
if not oauth:
oauth = default_provider(app)
app = prepare_app(app)
#app.before_request
def load_current_user():
user = User.query.get(1)
g.user = user
#app.route('/home')
def home():
return 'home'
#app.route('/oauth/authorize', methods=['GET', 'POST'])
#oauth.authorize_handler
def authorize(*args, **kwargs):
return True
Those
#app.route('/home') # and
#app.route('/oauth/authorize', methods=['GET', 'POST'])
have to be in another file.
My attempt was this, I tried to create a file for routers:
class Router():
def __init__(self, app, oauth):
self.app = app
self.oauth = oauth
#app.route('/home')
def home():
return 'home'
I'm getting this error:
NameError: name 'app' is not defined
Well, I see a package you can use for flask projects called Flask-Via [pypi], inspired by the Django URL configuration system and designed to add similar functionality to Flask applications that have grown beyond a simple single file application. The following example is given from the docs of this project:
from flask import Flask
from flask.ext.via import Via
from flask.ext.via.routers.default import Functional
app = Flask(__name__)
def foo(bar=None):
return 'Foo View!'
routes = [
Functional('/foo', foo),
Functional('/foo/<bar>', foo, endpoint='foo2'),
]
via = Via()
via.init_app(app, route_module='flask_via.examples.basic')
if __name__ == "__main__":
app.run(debug=True)
I think this is exactly what you want :) and you can move it to another python module for example called routers.py.

Deleting data in web.py

I'm following some of the recipes in the web.py cookbook after completing the tutorial. I am connected to my database all right, and can add items through web.py. However, I'm running into trouble when trying to delete items.
import web
db = web.database(dbn='mysql',user='root',pw='XXX',db='testdb')
render = web.template.render("templates/")
urls = (
'/','index',
'/add','add',
'/delete','delete',
)
class index:
def GET(self):
todos = db.select('todo')
return render.index(todos)
class add:
def POST(self):
i = web.input()
n = db.insert('todo',title=i.title)
raise web.seeother('/')
class delete:
def POST(self):
db.delete('todo',where="id=1")
if __name__ == '__main__':
app = web.application(urls,globals())
app.run()
When I go to the URL associated with the "delete" class, web.py returns "none". I assume this is the number of rows that have been deleted (i.e., none) but why isn't the item with id=1 being deleted?
Here's the cookbook entry for deleting data

python web.py form - not getting any value

I'm testing web.py and forms but I cant get any value in return. This is the code:
import web
from web import form
class add:
def GET(self):
f = login()
return render.formtest(f)
def POST(self):
f = login()
print f["ip"].value
return render.formpost(f)
render = web.template.render('templates/')
login = form.Form(
form.Textbox("ip", id="ip"),
form.Textbox('snmp_community'),
)
urls = ( '/','index', '/add', 'add')
app = web.application(urls,globals())
if __name__ == "__main__": app.run()
I followed this example: http://webpy.org/form but when I print the value of f["ip"].value or f.d.ip I always get "None".
Thank you for the help.
Here is a line from the web.py doc:
Note: You cannot access form values before having validated the form!
so you'll have to call f.validates() before you can access the posted data.

Google appengine rewrite question

How can I rewrite url for python:
http://localhost:8081/?page=1
to
http://localhost:8081/1
here is my code, but it's not working:
class MainPage(webapp.RequestHandler):
def get(self, page):
mypage = self.request.get('page')
self.response.headers['Content-Type'] = 'text/plain'
if mypage == "":
self.response.out.write('Hello, webapp World!')
else:
self.response.out.write('page is ' + mypage)
application = webapp.WSGIApplication([('/', MainPage),('/(\d+)', MainPage)], debug=True)
You can use regular expressions in your controller. It's not Apache-style URL rewriting per se, but it gets the job done. The rewritten parameter is passed as an argument to the handler.
class MyRequestHandler(webapp.RequestHandler):
def get(self, page):
self.response.headers['Content-Type'] = 'text/plain'
if not page:
self.response.out.write('Hello, webapp World!')
else:
self.response.out.write('page is ' + page)
url_map = [('/(\d+)', MyRequestHandler)]
application = webapp.WSGIApplication(url_map, debug=True)
See How to configure app.yaml to support urls like /user/<user-id>? for a similar application.
Assuming you're using webapp:
class Rewriter(webapp.RequestHandler):
def get(self):
self.redirect(self.request.get('page'))
application = webapp.WSGIApplication([('/', Rewriter)],)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
You've defined two mappings for your MainPage handler, one that will pass in no parameters ('/'), and one that will pass in one parameter ('/(\d+)'). Your handler, however, expects exactly one argument, named page.
You either need to use two different handlers, or supply a default value for the page argument, like this:
class MainPage(webapp.RequestHandler):
def get(self, page=None):
if not page:
self.redirect('/%s', self.request.get('page'))
return
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('page is ' + mypage)
For future reference, when you get a stacktrace, include it in your question! Saying "It's not working" and making us guess exactly what's going wrong isn't a good way to get useful answers to your question.

How to import modules into web.py templates?

I have following piece of code:
render = web.template.render('templates/')
app = web.application(urls, globals())
I read about template imports in the web.py cookbook.
Now, when I try to import re in a template:
render = web.template.render('templates/', globals={'re':re})
app = web.application(urls, globals())
I got an error:
<type 'exceptions.TypeError'> at /'dict' object is not callable
and this line showed in the traceback: app = web.application(urls, globals()).
But when I modify it:
app = web.application(urls)
the error is gone, and re is imported in my template.
I don't understand how globals={'re': re} in web.template.render breaks it?
Why I can't keep both globals as in second example?
I'm guessing there is something else you are doing in your script or template that is causing that error. If you showed the complete example, then it would be easier to see. Here is a working example:
import web
import re
urls = ('/', 'index')
render = web.template.render('templates/', globals={'re':re})
app = web.application(urls, globals())
class index:
def GET(self):
args = web.input(s='')
return render.index(args.s)
if __name__ == '__main__':
app.run()
And the template, index.html:
$def with(s)
$code:
if re.match('\d+', s):
num = 'yes'
else:
num = 'no'
<h1>Is arg "$:s" a number? $num!</h1>
Browse to http://localhost:8080/?s=123 to try it.

Categories

Resources