python web.py form - not getting any value - python

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.

Related

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

Access to session in flask_wtf

In forms.py I wanna get access to sessions.
this is forms.py code:
from flask_wtf import Form
from wtforms import SelectField,FileField,TextAreaField,TextField,validators
.
.
.
class Send(Form):
group = SelectField('Group',[validators.Required('you must select a group')],coerce=int,choices=c)
title = TextField('Title',[validators.Required('you must enter a title')])
content = TextAreaField('Content',[validators.Required('you must enter a content')])
attachment = FileField('Attachment')
But when I add this code :
from flask import session
uid = session.get('user_id')
It shows me this error:
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
So how can I solve it?
You should use uid = session.get('user_id') only on request, for example:
app = Flask(__name__)
#app.route('/')
def home():
'''dispatcher functions works with request context'''
uid = session.get('user_id')
return str(uid)
If this code calling not from request (another process, another thread, celery, unit test and etc), then you should create request context manually or avoid use context stack variables:
with app.test_request_context():
uid = session.get('user_id')
Ok , I find how to solve that problem.
I think one of the best way is to use session in the route file.
This is my form code:
from flask_wtf import Form
from wtforms import SelectField
class Test(Form):
name = SelectField('Name')
So I have an app with "our" name, I have access to session in this app:
from flask import Blueprint,session,render_template
from form import Test
our = Blueprint('our',__name__)
#our.route('/')
def index():
form = Test()
#session['name'] = 'hedi'
if session.get('name').lower() == "morteza":
form.name.choices = ((1,'mori'),(2,'hedi'))
else:
form.name.choices = ((1,'you'))
return render_template('index.html',form=form)
#return str(session.get('name'))
Now I changed my form field data via app. form.name.choices=....

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

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.

Rendering multiple templates with web.py

Ive recently gotten into Webdesign in Python, I've tried multiple frameworks but web.py seems to be my favorite except for one problem. I cant seem to figure out how to make multiple pages with multiple templates....
here is my code so far:
import web
urls = (
'/', 'index', '/login/', 'login'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class index():
def GET(self):
return render.index()
class login():
def GET(self):
return render.login()
if __name__ == '__main__':
app.run()
I get an error when I try to go to the login page :/
Try changing your url mapping:
urls = (
'/', 'index',
'/login/?', 'login',
)
/login/? will work for /login and /login/ url paths.
It will be better if you show an exception that you get.

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.

Categories

Resources