Web.py How to access render function in this case - python

I am new to Python and Web.py, but I am tearing my hair out over this issue. I have a code layout where I have my app.py file in the root of my site. All the pages are in a sub director, named pages. Here is my app.py code
import web
import page.index
urls = (
'/', 'page.index.index',
)
render = web.template.render('templates/', base = "layout") # Start the template
app = web.application(urls, globals()) # Start the app
if __name__ == "__main__":
app.run()
Now, it executes perfectly. Now, in the index.py file, this is my code:
class index:
def GET(self):
testing = 'Hello World'
return render.index(testing)
The error I am getting is this:
<type 'exceptions.NameError'> at /
global name 'render' is not defined
Python /Volumes/Local Disk 2/Work/Casting Board/com/index.py in GET, line 3
Web GET http://127.0.0.1:8080/
Basically, I am trying to access the function ( or it is method or class. Just coming from PHP so don't know the terminally) render from a moucle called page.index. How can I get around this?

In the index.py page, should you include from web.template import render ?

Presuming web.template.render() returns an object containing an index() method (I'm not familiar with web.py), you'll need to tell Python where to find this object.
In index.py:
import app
Then:
return app.render.index(testing)

You can just include you index class (index.py) within your app.py file. Importing the web module then will bring in the definition of the function "render" at the beginning of your code.

Related

Having trouble with Flask in python, either says render_template doesn't exist, or that my template doesn't exist

I am doing an assignment to integrate a python script with HTML templates, and while the IDE is giving me no errors, when I try to actually run the website it gives me an "internal server error" and in the debug menu it says either that it doesn't recognize the Flask command "render_template" or doesn't recognize the HTML file it's supposed to render. The HTML file is stored both in the same folder as the python file and a copy is stored in a seperate "templates" folder located in the same folder as the python file. I really have no idea what's going on, the teacher has been no help.
I tried renaming the files, spell checked the imports repeated, checked all the commands, made copies of the python and Html files to see if the directorry was the problem. I really am not sure what else to try
...from flask import Flask
...from flask import render_template
...from flask import request
...from flask import flash
...import datetime
...app = Flask(__name__)
```#app.route('/')
...#the home page
...def home():
... return render_template('home_page.html')
```#app.route('/clock/')
...#the clock site
...def time_site():
... return date_and_time()
...def date_and_time():
... cur_time = str(datetime.now())
...return render_template('clock.html', cur_time)
```if __name__ == "__main__":
...app.run()

Can't show html using Flask

So I have been trying to get used to Flash in python but I've come across a problem. I want that when http://localhost:5000/ is inserted in the browser a html page is displayed. I've tried multiple ways to do this like using the render_template() but that returns me a jinja2.exceptions.TemplateNotFound: index.html. I've also tried a simple return redirect() but that throws something saying the adress was not recognized or understood. When I tried using the url_for() it threw 404 - not found. I really have no idea how to fix this.
# htppserver.py
import flask
import threading
app = Flask(__name__, template_folder="Dashboard/website")
#app.route("/site", methods=["GET"])
#app.route("/", methods=["GET"])
def get_site():
return render_template("index.html")
x = threading.Thread(target=app.run)
x.start()
Currently my dir system looks something like this
main_folder # This is the working directory accordingly to os.getcwd()
├──cogs
│ └──httpserver.py # Source code is here
└──Dashboard
└website
├──...
├──index.html # This is the file I want to show
└──...
Thanks
put your html files in a folder called "templates" in the same directory as the python file that serves

Dynamic python/flask route function naming

first off, a disclaimer: I'm not well versed in python or flask, so bear with me.
I'm trying to put together a minimal API using flask, i was planning to dynamically generate routes and their associated procs from the contents of a subdirectory.
The code looks something like this:
from flask import Flask
import os
app = Flask(__name__)
configs = os.getcwd() + "/configs"
for i in os.listdir(configs):
if i.endswith(".json"):
call = "/" + os.path.splitext(i)[0]
#app.route(call, methods=['POST'])
def call():
return jsonify({"status": call + "Success"}), 200
The plan being to iterate over a bunch of config files and use their naes to define the routes. Now, this works for a single config file, but wont work for multiple files as I end up trying to overwrite the function call that is used by each route.
I can factor out most of the code to a separate function as long as i can pass in the call name. However it seems that however i go about this i need to dynamically name the function generated and mapped to the route.
So, my question is: how can use the contents of a variable, such as 'call' to be the function name?
i.e. something like
call = "getinfo"
def call(): # Effectively being evaled as def getinfo():
Everything i've tried hasn't worked, and i'm not confident enough in my python syntax to know if it's because i'm just doing something silly.
Alternatively is there another way to do what i'm trying to achieve?
Thanks for all and any feedback!
Thanks for the help. I've moved to one route and one handler and building up the file list, and handling of the request paths, etc separately.
This is a sanitized version of the model i now have:
from flask import Flask
import os
calls = []
cfgs = {}
app = Flask(__name__)
configs = os.getcwd() + "/configs"
for i in os.listdir(configs):
if i.endswith(".json"):
cfgs[call] = os.path.splitext(i)[0]
calls.extend([call])
#app.route('/<call>', methods=['POST'])
def do(call):
if call not in calls:
abort(400, "invalid call")
# Do stuff
return jsonify({"status": call + "Success"}), 200
if __name__ == '__main__':
app.run(debug=True)
So, thanks to the above comments this is doing what i'm after. Still curious to know if there is any way to use variables in function names?

Pyramid error: AttributeError: No session factory registered

I'm trying to learn Pyramid and having problems getting the message flash to work. I'm totally new but read the documentation and did the tutorials.
I did the tutorial on creating a wiki(tutorial here, Code here ). It worked great and was pretty easy so I decided to try to apply the flash message I saw in todo list tutorial I did(tutorial here, full code is in a single file at the bottom of the page). Basically when a todo list is created, the page is refreshed with a message saying 'New task was successfully added!'. I wanted to do that everytime someone updated a wiki article in the wiki tutorial.
So I re-read the session section in the documentaion and it says I really just need to do this:
from pyramid.session import UnencryptedCookieSessionFactoryConfig
my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
from pyramid.config import Configurator
config = Configurator(session_factory = my_session_factory)
then in my code I need to add: request.session.flash('New wiki was successfully added!') but I get a error everytime: Pyramid error: AttributeError: No session factory registered
Here's my function(its the exact same from the tutorial except for the request.session.flash part):
#view_config(route_name='edit_page', renderer='templates/edit.pt', permission='edit')
def edit_page(request):
name = request.matchdict['pagename']
page = DBSession.query(Page).filter_by(name=name).one()
if 'form.submitted' in request.params:
page.data = request.params['body']
DBSession.add(page)
request.session.flash('page was successfully edited!')
return HTTPFound(location = request.route_url('view_page',
pagename=name))
return dict(
page=page,
save_url = request.route_url('edit_page', pagename=name),
logged_in=authenticated_userid(request),
)
(note: One thing that I think I could be doing wrong is in the todo example, all the data is in one file, but in the wiki example there are several files..I added my session imports in the view.py file because the flash message is being generated by the view itself).
What am I doing wrong? Any suggestions?
The code you provided is just an example, of course you need to apply it in a correct place. In Pyramid you should (in simple cases ;) have only 1 place in your code where you create just 1 Configurator instance, in the tutorial it is in the main function. A Configurator does not do anything by itself, except create a WSGI application with make_wsgi_app.
Thus, to add sessions there, modify wiki2/src/views/tutorial/__init__.py as follows:
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramid.session import UnencryptedCookieSessionFactoryConfig
from .models import DBSession
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
config = Configurator(settings=settings, session_factory=my_session_factory)
...

web.py / pythonpath confusion

Im playing around with web.py as a lightweight web framework. Im having problems when i attempt to move the actual implementation of my page into a separate file instead of the root file. As a demonstration, My core.py file looks like this:
import web, sys, os
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
urls = (
'/', 'index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
if __name__ == "__main__":
app.run()
ive moved my implementation into a file called index.py at the same level as core.py. My implementation looks like this:
class index:
def GET(self):
return "Hello world"
however, whenever i run my application, i get an error:
<type 'exceptions.KeyError'> at /
can anybody tell me what is going on?
According to http://webpy.org/tutorial3.en#urlhandling, web.py does a lookup for the classes you specified in your urls in the global namespace.
In your core.py there is no class named index (after you moved it), that's what causes this keyerror. In my test I could fix that by importing the index class in core.py.
from index import index
(I haven't used web.py before, so please correct me if I'm wrong)
You can add dots to crawl into modules. So say you have a folder controllers with a file named file.py and you wanted to access the controller named index:
from controllers import *
urls = (
'/', 'controllers.file.index'
)
I'm guessing the bug is in your template. I hit this error when if forgot a ':' on an if statement in my template.

Categories