Search code examples
pythonwebapp2

Need to access self.request.GET from main.py in lib.py


I need to do calculations among other things within lib.py and I need to access the user input data within main.py for it, because it needs to be that way. How do I do this?

doing from main import MainHandler in lib.py and then calling it "works" in the sense that it doesn't give any code errors, but displays a blank page when done that way and I get a log error saying that I cannot import it.

main.py

import webapp2
from lib import FormData
from pages import FormPage
from pages import ResultsPage


class MainHandler(webapp2.RequestHandler):
    def get(self):
        f = FormPage()
        s = ResultsPage()
        fd1 = FormData()

    if self.request.GET:
        fd1.name = self.request.GET['name']
        fd1.email = self.request.GET['email']
        fd1.weight = self.request.GET['weight']
        fd1.height = self.request.GET['height']
        self.response.write(s.second_page(fd1.name, fd1.email, fd1.weight, fd1.height))
    else:
        self.response.write(f.form_page)

app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)

lib.py

class FormData(object):
    def __init__(self):
        pass

I need to be able to access:

fd1.name = self.request.GET['name']
fd1.email = self.request.GET['email']
fd1.weight = self.request.GET['weight']
fd1.height = self.request.GET['height']

In lib.py


Solution

  • Your if/else statement is outside the get method, so it shouldn't even work properly.

    I think the most clean way would be to pass the request data to the FormData class already in the initialiser. So the code would look like this:

    main.py

    import webapp2
    from lib import FormData
    from pages import FormPage
    from pages import ResultsPage
    
    
    class MainHandler(webapp2.RequestHandler):
        def get(self):
            f = FormPage()
            s = ResultsPage()
            fd1 = FormData(data=self.request.GET)
    
            if fd1.name: # This is None, if form has not been submitted
                self.response.write(s.second_page(fd1.name, fd1.email, fd1.weight, fd1.height))
            else:
                self.response.write(f.form_page)
    
    app = webapp2.WSGIApplication([
        ('/', MainHandler)
    ], debug=True)
    

    lib.py

    class FormData(object):
    
        def __init__(self, data):
            self.name = data.get('name')
            self.email = data.get('email')
            self.weight = data.get('weight')
            self.height = data.get('height')
    

    As a side note, I don't really know this webapp2 framework, so there might be a better way to do this.