I'm a bit new to the MVC style of programming, and am working on
a Python/GAE/jinja2/webapp2 starter app to get my feet wet.
Is there any reason for me to be working at the Werkzeug level initially?
Or is that something to get into if webapp2 doesn't let me do something that I need to do?
I'm trying to understand the routing aspect, and it seems like that can
be handled in various ways possibly. Is webapp2 a good place to start intitially with that,
and then if it needs to get more complex, what would be the next level if needed for more
complex URL routing?
I saw this on the webapp2 site docs:
app = webapp2.WSGIApplication([
(r'/', HomeHandler),
(r'/products', ProductListHandler),
(r'/products/(\d+)', ProductHandler),
])
Is it not sequential in how it looks through them, in which case it would
be the more detailed line first in the list?
But the app.yaml file is sequential, right?
But only within the groupings - handlers, libraries, etc...?
You can really work at whatever level you are comfortable (mostly dictated by your requirements). How routing is implemented is very dependent on what lib/tools you use.
Pyramid and bobo are altenatives to the few you have listed, and implement routing completely differently.
app.yaml is processed in order, and as far as routing is concerned handlers are all that matter.
My personal preference for routing is anything that doesn't use regex's ;-)
(See pyramid and bobo)
I tend to have as few handlers listed as I can in app.yaml, and move the rest of the routing behaviour into the sprecific handler.
Rgds
Tim
Related
I have read the official Flask documentation on Blueprints and even one or two blog posts on using them.
I've even used them in my web app, but I don't completely understand what they are or how they fit into my app as a whole. How is it similar to an instance of my app but not quite? The documentation is comprehensive but I seek a layman explanation or an enlightening analogy to spark it for me. I was sufficiently perplexed when a colleague asked me to explain a Flask blueprint to them that I elected to ask here.
A blueprint is a template for generating a "section" of a web application. You can think of it as a mold:
You can take the blueprint and apply it to your application in several places. Each time you apply it the blueprint will create a new version of its structure in the plaster of your application.
# An example
from flask import Blueprint
tree_mold = Blueprint("mold", __name__)
#tree_mold.route("/leaves")
def leaves():
return "This tree has leaves"
#tree_mold.route("/roots")
def roots():
return "And roots as well"
#tree_mold.route("/rings")
#tree_mold.route("/rings/<int:year>")
def rings(year=None):
return "Looking at the rings for {year}".format(year=year)
This is a simple mold for working with trees - it says that any application that deals with trees should provide access to its leaves, its roots, and its rings (by year). By itself, it is a hollow shell - it cannot route, it cannot respond, until it is impressed upon an application:
from tree_workshop import tree_mold
app.register_blueprint(tree_mold, url_prefix="/oak")
app.register_blueprint(tree_mold, url_prefix="/fir")
app.register_blueprint(tree_mold, url_prefix="/ash")
Once it is created it may be "impressed" on the application by using the register_blueprint function - this "impresses" the mold of the blueprint on the application at the locations specified by url_prefix.
As pointed out in a comment by #Devasish, this article provides a good answer:
http://exploreflask.com/en/latest/blueprints.html
Quoting from the article:
An example of this would be Facebook. If Facebook used Flask, it might
have blueprints for the static pages (i.e. signed-out home, register,
about, etc.), the dashboard (i.e. the news feed), profiles
(/robert/about and /robert/photos), settings (/settings/security and
/settings/privacy) and many more. These components all share a general
layout and styles, but each has its own layout as well
This is a very good interpretation, especially the part "if Facebook used Flask". It gives us a concrete situation to visualize how Blueprint actually works.
For bigger projects, all your code shouldn't be in the same file.
Instead you can segment or split bigger codes into separate files, mostly based on functionality. Like bricks forming a wall.
A simple Flask app
app = Flask(__name__)
A blueprinted Flask app
import from_any_module.part_1
import from_other_module.part_2
app = Flask(__name__)
app.register_blueprint(part_1)
app.register_blueprint(part_2)
A blueprint in the above app
from flask import Blueprint
part_1 = Blueprint(part_1)
#part_1.route('/url')
def function()
return view
I too just stumbled up this myself and was confused after reading a few of the documentation sources. At first I thought it was like C#/Java OOP Interface Implementation style where you define some stuff but dont have to worry about it implementation details til later. However, I stumbled up this page which puts it in very very laymens (and quite hilarious present-day events) terms. https://hackersandslackers.com/flask-blueprints/
Essentially one benefit that is mentioned in the link and provides me a clear idea of it's real world usage is that I can effectively logically organize/divide the app into several parts that only need to be concerned with it's own affairs. So it provides some designed encapsulation.
Edit: I'm currently using it to segment out my webapps code. It was good decision too because I found the lead designer wants to make the frontend in Vue.js. Which I havent used yet but looking at it's project files would look far more messy and probably provide many naming collision prone instances due to files with similar names
A Flask blueprint helps you to create reusable instances of your application. It does so by organizing your project in modules. Those modules are then registered the main application. They help in creating an application factory.
I want to switch from Rails to Django, to broaden my mind, and a question has bobbed up in my mind.
My Rails app is quite a mess, since my hobby-based development approach is a patch-and-glue one. I have seen very early that Django divied between a project and an app. According to their site, a project is made of many apps, and one app can be used for many projects.
This intrigued me, since that would made the lines between my site's areas clearer. I tried to find some more examples and information on that, but I couldn't answer my question, which is:
How big/small is such an app? Are they able/supposed to interact closely?
It is, for example smart to have one app to deal with user's profiles, and another app to deal with blog-posts and comments, from those users? (In my site, a user can have several blogs, with different profiles). Or are they meant to be used otherwise?
A django App is a fancy name for a python package. Really, that's it. The only thing that would distinguish a django app from other python packages is that it makes sense for it to appear in the INSTALLED_APPS list in settings.py, because it contains things like templates, models, or other features that can be auto-discovered by other django features.
A good django app will do just one thing, do it well, and not be tightly coupled to any other app that might use it. A wide variety of apps are provided with django in the contrib namespace that follow this convention.
In your example, a good way to devise apps is to have one for user profiles (or use one of the many existing profile apps), one app for blog posts (or one of the many that already do this), one app for comments, separate from blog posts (again, you can use an existing app for this), and finally, a very tiny app that ties the three together, since they don't and shouldn't depend on each other directly.
The purpose of using app's is to make them reusable. Django likes DRY principle DRY stands for DO NOT repeat yourself
An app should be as small as it can, and loosely coupled. So, for an app should not need another app to work properly.
Django recommends writing an app for each table (well, not always, but as soon as you want to grow your app, you will definitely need to divide tables to pair apps. Or else you will have hard time for maintaining your code.)
You can, for example, create an app for users, an app for sales, an app for comments, an app for articles. It will be easier to maintain your code and if you have done it right, you can use the app in other project with a little (if any) modification in the app.
Project's are, compilation of app's. Users app, articles app, comments app can come together an make a project, or in other words, a website.
If you want to learn django, I suggest you to check out:
http://www.djangobook.com/
http://docs.djangoproject.com/
One word of advice, do not, in any case, copy/paste. Not only your code has great chance to fail, but you will not know what the code is doing. If you are going to use someone elses code in your project, at least type them, this will make you understand what the code is doing, or at least, it will give an idea.
Writing your own code is always better for maintance, but this does not mean that you should reinvent the world, you can use libraries, look at their documentation to use it properly.
Documentations, tutorials are you best friend.
Good luck.
A project is basically a place where your project lives...in your project you setup your url's, project settings, etc.
An app defines its own data models and views to be used within a project. You can move these between projects if you like.
I highly recommend running through the tutorials from the Django site as they will show you what a project and app are, how to manage both, how to use the admin panel, how to make the app usable in multiple projects, etc.
A portal = A django project
A ads system, gallery photos, catalog of products = Apps
I'm developing an app (an API) in python and I would like to offer some of its functionality through a web interface (like web services do).
I've been looking at django, but I don't know if really fits well in my idea. I only want to create a web page that invokes to my API methods in order to acomplish the functionality that offers that web page. But, after followed the tutorial, I feel a little confused about the point of django. It seems to me to be more related with an ORM than a classic web application.
Is django a solution so heavy for such a simple development (as I mentioned, make calls to my API through the web)? Do I always have to use a database?
Thanks.
I love django but there is an lot of it to get your head around! If you don't want the database bit, focus on urls.py and views.py that will process your urls and return the info you want as an http response.
eg. urls.py
urlpatterns += patterns('myapp.views',
url(r'^getstuff/$', 'getstuff' ),
)
in views.py
def getstuff(request):
do whatever in python
return HttpResponse(stuff to return)
You don't need to use database in Django projects.
Basically django comes with some standardized architecture that follows MVC pattern (or MVT as sometimes described). This includes models, views, url dispatching, templates, etc.
Probably you need to do following things to accomplish your task:
create url definition in urls.py
to some django view
write
django view that call somehow your
api and displays result as a web
page
you don't need models and database at all but you need to get familliar with views, urls, templates. It might look like a big machinery for your simple case but if you have some time I encourage you to these django basics.
If you are looking for somethin much simpler I heard about webpy project. This might be better option if you need something really simple.
An important question is: Do you want the web services to be provided by a full-featured server like Apache, or are you just looking at the "web server" to be a thread (or equivalent) in your program?
If you want to run Apache, then I'd recommend something like Werkzeug, which will handle most of the WSGI stuff for you. For templating, I've heard good things about Jinja2.
If that is too much, and all you want is a lightweight, simple server (something that, say, just spits out some HTML or XML when asked, and doesn't need any fancy URL handling), you can use the SimpleHTTPServer or CGIHTTPServer modules that ship with Python.
Django is a full-featured, integrated package that provides almost everything you need to write database-backed web applications. While its various components can be used in isolation, if you're only using one thing (the template and view engines, in your case), it is probably overkill.
No need for a framework at all. Raw wsgi isn't hard but a little verbose. So I like to use WebOb
Here's Raw wsgi
def application(environ, start_response):
start_response("200 OK", [])
return ["<html><body><h1>Hello World</h1></body></html>"]
Here's the webob version
from webob.dec import wsgify
from webob import Request
#wsgify
def application(request):
return Response("<html><body><h1>Hello World</h1></body></html>")
That's enough to run under apache mod_wsgi, and there are plenty of libraries that you can use that expect/produce webob Request and Responses. Anything that Turbogears 2 or repoze.bfg uses is fair game at that point.
You definitely don't have to use a database with Django. Whether it fits your needs, only you can tell. There are other Python web frameworks that you can use.
For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh.
How do I integrate the simple_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point.
My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions.
Thanks for the help.
EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.
The other answers give good recommendations for what you probably want to do towards your "eventual goal", but, if you first want to persist with wsgiref.simple_server for an instructive while, you can do that too. WSGI is the crucial "glue" between web servers (not just the simple one in wsgiref of course -- real ones, too, such as Apache or Nginx [both with respective modules called mod_wsgi] as well as, for example, Google App Engine -- that one offers WSGI, too, as its fundamental API) and web applications (and frameworks that make it easier to write such applications).
Everybody's recommending various frameworks to you, but understanding WSGI can't hurt (since it will underlie whatever framework you eventually choose). And for the purpose of such understanding wsgiref.simple_server will serve you for a while longer, if you wish.
Essentially, what you want to do is write a WSGI app -- a function or class that takes two parameters (an "enviroment" dictionary, and a "start response" callable that it must call back with status and headers before returning the response's body). Your "WSGI app" can open your index.py or whatever else it wants to prep the status, headers and body it returns.
There's much more to WSGI (the middleware concept is particularly powerful), though of course you don't have to understand it very deeply -- only as deeply as you care to! See wsgi.org for tutorials &c. Gardner's two-part article, I think, is especially interesting.
Once (and if that's your choice) you understand WSGI, you can better decide whether you want it all hidden in a higher level framework such as Django (so you can focus on application-level issues instead) or use a very light and modular toolbox of WSGI utilities such as Werkzeug -- or anything in-between!-)
I would recommend Django.
"Obviously with PHP, you simply make sure its installed on your server and you start writing the code."
Not true with Python. Python is just a language, not an Apache plug-in like PHP.
Generally, you can use something like mod_wsgi to create a Python plug-in for Apache. What you find is that web page processing involves a lot of steps, none of which are part of the Python language.
You must use either extension libraries or a framework to process web requests in Python. [At this point, some PHP folks ask why Python is so popular. And the reason is because you have choices of which library or framework to use.]
PHP parses the request and allows you to embed code in the resulting page.
Python frameworks -- generally -- do not work this way. Most Python frameworks break the operation down into several steps.
Parsing the URL and locating an appropriate piece of code.
Running the code to get a result data objects.
Interpolating the resulting data objects into HTML templates.
"My goal is to begin building simple web applications into my pre-existing static XHTML pages."
Let's look at how you'd do this in Django.
Create a Django project.
Create a Django app.
Transform your XTHML pages into Django templates. Pull out the dynamic content and put in {{ somevariable }} markers. Depending on what the dynamic content is, this can be simple or rather complex.
Define URL to View function mappings in your urls.py file.
Define view functions in your views.py file. These view functions create the dynamic content that goes in the template, and which template to render.
At that point, you should be able to start the server, start a browser, pick a URL and see your template rendered.
"write a basic message board in Python."
Let's look at how you'd do this in Django.
Create a Django project.
Create a Django app.
Define your data model in models.py
Write unit tests in tests.py. Test your model's methods to be sure they all work properly.
Play with the built-in admin pages.
Create Django templates.
Define URL to View function mappings in your urls.py file.
Define view functions in your views.py file. These view functions create the dynamic content that goes in the template, and which template to render.
Take a look at CherryPy. It's a nice http framework.
It depends on what you want to achieve,
a) do you want to just write a web application without worrying too much abt what goes in the background, how request are being handled, or templates being rendered than go for a goo webframework, there are many choices simple http server is NOT one of them. e.g. use django, turbogears, webpy, cheerpy, pylons etc etc
see http://wiki.python.org/moin/WebFrameworks for full list
b) if you want to develope a simple web framework from start so that you understand internals and improve you knowledge of python, then I will suggest use simple http server
see
how can you create a URL scheme so that URLs are dispatched to correct python function,
see how can you render a html
template e.g. containing place
holder variables $title etc which
you can convert to string using
string.Template
b) would be difficult but interesting exercise to do, a) will get you started and you may be writing web apps in couple of days
I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications.
Let's take a kind of SO as an example. Which applications would you use?
I'd say there should be the applications "users" and "questions". But what if there was a topic system with static articles, too. Maybe they also could receive votes.
How to build the apps structure then? One app for "questions", "votes" and "topics" or just one app "content"?
I have no idea what to do. Maybe it's because I know not very much about Django yet, but I'm interested either...
There aren't hard-and-fast rules, but I would say it's better to err on the side of more specialized applications. Ideally an application should handle just one functional concern: i.e. "tagging" or "commenting" or "auth/auth" or "posts." This type of design will also help you reuse available open source applications instead of reinventing the wheel (i.e. Django comes with auth and comments apps, django-tagging or django-taggable can almost certainly do what you need, etc).
Generic foreign keys can help you decouple applications such as tagging or commenting that might be applied to models from several other applications.
You should try and separate the project in as much applications as possible. For most projects an application will not contain more than 5 models. For example a project like SO would have separate applications for UsersProfiles, Questions, Tags (there's a ready one in django for this), etc. If there was a system with static pages that'd be a separate application too (there are ready ones for this purpose). You should also try and make your applications as generic as possible, so you may reuse them in other projects. There's a good presentation on reusable apps.
Just like any set of dependencies... try to find the most useful stand-alone aspects of the project and make those stand-alone apps. Other Django Apps will have higher level functionality, and reuse the parts of the lowest level apps that you have set up.
In my project, I have a calendar app with its own Event object in its models. I also have a carpool database set up, and for the departure time and the duration I use the calendar's Event object right in my RideShare tables. The carpooling database is calendar-aware, and gets all the nice .ics export and calendar views from the calendar app for 'free.'
There are some tricks to getting the Apps reusable, like naming the templates directory: project/app2/templates/app2/index.html. This lets you refer to app2/index.html from any other app, and get the right template. I picked that one up looking at the built-in reusable apps in Django itself. Pinax is a bit of a monster size-wise but it also demonstrates a nice reusable App structure.
If in doubt, forget about reusable apps for now. Put all your messages and polls in one app and get through one rev. You'll discover during the process what steps feel unnecessary, and could be broken out as something stand-alone in the future.
A good question to ask yourself when deciding whether or not to write an app is "could I use this in another project?". If you think you could, then consider what it would take to make the application as independent as possible; How can you reduce the dependancies so that the app doesn't rely on anything specific to a particular project.
Some of the ways you can do this are:
Giving each app its own urls.py
Allowing model types to be passed in as parameters rather than explicitly declaring what models are used in your views. Generic views use this principle.
Make your templates easily overridden by having some sort of template_name parameter passed in your urls.py
Make sure you can do reverse url lookups with your objects and views. This means naming your views in the urls.py and creating get_absolute_url methods on your models.
In some cases like Tagging, GenericForeignKeys can be used to associate a model in your app to any other model, regardless of whether it has ForeignKeys "looking back" at it.
I'll tell you how I am approaching such question: I usually sit with a sheet of paper and draw the boxes (functionalities) and arrows (interdependencies between functionalities). I am sure there are methodologies or other things that could help you, but my approach usually works for me (YMMV, of course).
Knowing what a site is supposed to be is basic, though. ;)