Gimme’s API Documentation¶
Application Creation¶
- class gimme.app.App(name='gimme', engine=<gimme.engines.Jinja2Engine object at 0x2c7c310>, logger=<class 'gimme.servers.logger.logger.SysLogger'>)[source]¶
The central class that ties a Gimme application together.
There are a few configuration parameters that may be passed to App objects upon instantiation, although most of the configuration is done via middleware.
Basic usage may look something like the following:
app = App('some_app') # Add middleware. app.use(gimme.middleware.session()) # Add routes to a controller that we have not shown here. app.routes.get('/', SomeController.index + 'index.html') app.routes.get('/about', SomeController.about + 'about.html') # Start the app's development web server. app.listen()
Variables: - dirname – Stores the path information from where the app was started from.
- routes – An instance of gimme.routes.Routes, which is used for mapping routes to controllers, etc.
Parameters: - name (str) – The name to use for the app in the logger.
- engine – The template engine adapter to use.
- logger – The log class to use.
- get(key)[source]¶
Gets a key from the app, previously set with set().
Parameters: key – The key to fetch
- listen(port=8080, host='127.0.0.1', http_server=<class 'gimme.servers.http.server.HTTPServer'>)[source]¶
Starts the built-in development webserver.
Parameters:
Requests, Responses, and Controllers¶
Of course, one of the primary things that any web framework must do, is handle requests and make responses. The MVC paradigm generally ties these two elements together via the controller. Gimme is no different.
Typically, the application developer will create controllers and their corresponding methods, then create routes to those methods. A very simple application may do something like the following:
app = gimme.App()
class RootController(gimme.Controller):
def index(self):
self.response.headers['Some-Header'] = 'value'
return {
'today': datetime.datetime.now(),
'user_name': self.request.session['user_name']
}
app.routes.get('/', RootController.index + '/path/to/template.html')
There’s really not much more to it than that (although I do recommend checking out the documentation for the gimme.request.Request and gimme.response.Response classes).
One important gotcha: controller methods that are to be bound to routes should NEVER start with _
- class gimme.controller.Controller(app, request, response)[source]¶
Like most frameworks, the controller is what bridges the gap between the model (business logic) and the view. In Gimme, one thing that is a little different from the classic MVC methodology is that controllers are not directly tied to views. This is explained further in the gimme.routes.Routes documentation.
Controllers are instantiated automatically by Gimme on an as-needed basis. If a controller’s method is needed to fulfill a request, the controller will be instantiated and the method called and its data returned. This means that controllers are instantiated per request, as opposed to once, as the application is started.
One thing to note is that, while Gimme instantiates controllers automatically, in order to perform unit tests, you must instantiate controllers in your tests. This can be done like so:
controller = YourController(your_app, request_obj, response_obj)
Of course, to do the above, you must have request and response objects. To fetch these objects, the easiest way is generally via the gimme.routes.Routes.match() method:
request, response = your_app.routes.match(wsgi_environ)
(Where the wsgi_environ variable is a dictionary-like object with necessary WSGI environ parameters, such as PATH_INFO, REQUEST_METHOD, etc.)
One other thing that may be worth noting is that this class uses a custom metaclass that, upon definition, scans for any method whose name does not start with a _, and replaces it with an instance of gimme.controller.ControllerMethod.
Variables: - app – The gimme app.
- request – The request object.
- response – The response object.
- class gimme.controller.ControllerMethod(cls, fn)[source]¶
ControllerMethod objects wrap regular controller methods, as defined by the application programmer.
In order to allow greater flexibility and expressiveness, all controller methods whose name do not start with _ are replaced with instances of ControllerMethod. These objects can be called just as the controller methods can, but in addition, other methods and operators are made available.
What all this means, in practice, is that you can do things like this in your route definitions:
app.routes.get('/', RootController.index + 'index.html')
I hope to elaborate on this and how it works in the future.
- __add__(other)[source]¶
Creates a new gimme.controller.MethodRenderer object with the other object as the first renderer. Or, if other is a string, instantiates a gimme.renderers.Template object with the string and passes that to the gimme.controller.MethodRenderer instead.
Example:
method_renderer = SomeController.some_method + gimme.Template('index.html') # or, a shortcut: method_renderer = SomeController.some_method + 'index.html'
Parameters: other – Either a string or an instance of gimme.renderers.BaseRenderer.
- __eq__(content_type)[source]¶
Returns a gimme.renderers.Format object that responds to HTTP Accept headers as specified by content_type.
Example:
format_obj = YourController.your_method == 'text/html'
Parameters: content_type (str) – The content type to customize format to.
- __weakref__¶
list of weak references to the object (if defined)
- compress()[source]¶
Returns a gimme.controller.MethodRenderer object with a gimme.renderers.Compress renderer.
- json()[source]¶
Returns a gimme.controller.MethodRenderer object with a gimme.renderers.Json renderer.
- template(template_path)[source]¶
Returns a gimme.controller.MethodRenderer object with a gimme.renderers.Template renderer directed at the path provided by template_path.
Parameters: template_path (str) – Where to point the template to.
- class gimme.controller.MethodRenderer(items=[])[source]¶
The MethodRenderer provides an interface for multiple renderers to all manipulate the controller method’s output in an orderly fashion.
It should be noted that the MethodRenderer class inherits from list(). The first item in the list should always be an instance of gimme.controller.ControllerMethod. Every other item should inherit from gimme.renderers.BaseRenderer.
- __add__(other)[source]¶
Adds another BaseRenderer to the list.
Parameters: other (BaseRenderer) – The renderer to add. Returns: self
- __call__()[source]¶
Calls the ControllerMethod and then calls render() on each of the BaseRenderer objects.
Returns: The final output of the execution chain described above.
- __eq__(content_type)[source]¶
Returns a Format object with all of the renderers in this object inside it. Sets the Format content type to content_type.
This is typically used in something like the following:
app.routes.get('/', SomeController.index + ( (SomeController.index == 'text/plain') | # <-- (SomeController.index.json() == 'application/json') | (SomeController.index.template('template.html') == 'text/html') ))
Parameters: content_type (str) – The content type to set the Format object to. Returns: A Format object.
- __weakref__¶
list of weak references to the object (if defined)
- class gimme.request.Request(app, environ, match=None)[source]¶
The Request class is responsible for parsing the request headers and body into Pythonic shindigs that are (supposed to be) very easy to work with.
Variables: - app – The Gimme application.
- environ – The WSGI environ dict.
- headers – The request headers (an instance of gimme.headers.RequestHeaders).
- wsgi – The WSGI headers. Also an instance of gimme.headers.RequestHeaders.
- params – A gimme.dotdict.DotDict of the parameters from the route URI.
- query – The query string in a dictionary-like object.
- accepted – A handy parsing of the HTTP “Accept” header. An instance of gimme.parsers.accepted.AcceptedList.
- accepted_languages – A handy parsing of the HTTP “Accept-Language” header. An instance of gimme.parsers.accepted.AcceptedList.
- accepted_charsets – A handy parsing of the HTTP “Accept-Charset” header. An instance of gimme.parsers.accepted.AcceptedList.
- cookies – The raw HTTP “Cookie” string.
- type – Either an instance of gimme.parsers.contenttype.ContentType if the HTTP header “Content-Type” is present or None.
Parameters: - app – The Gimme application.
- environ – The WSGI environ dict.
- match – The matching route, if any.
- accepts(content_type)[source]¶
Tests if a given content type is in the HTTP “Accept” header.
Parameters: content_type – The content type to check for.
- accepts_charset(charset)[source]¶
Tests if a given charset is in the HTTP “Accept-Charset” header.
Parameters: charset – The charset to check for.
- accepts_language(language)[source]¶
Tests if a given language is in the HTTP “Accept-Language” header.
Parameters: language – The language to check for.
- param(key)[source]¶
A simple helper method that looks for a given key in three places: self.params, self.body, and self.query.
Parameters: key – The parameter to look for.
- class gimme.response.Response(app, route, request)[source]¶
The Response class is responsible for aggregating all of the information required for generating a response and for rendering said response.
Variables: - app – The Gimme application.
- route – The route that matched the request/response objects.
- request – The request object.
- headers – An instance of gimme.headers.ResponseHeaders that will eventually be converted to a string appropriate for the HTTP response headers.
- body – The body of response.
- locals – An instance of gimme.dotdict.DotDict that is intended to store arbitrary information that is unique to a given response object.
- attachment[source]¶
A helper for setting the “Content-Disposition” and “Content-Type” HTTP headers for a given file. This makes it easy to pass a file to the client for downloading.
Note, this is implemented as a setter-only property. In other words, you cannot “get” the attachment information with this property, but only set it.
This is valid:
response.attachment = "something.jpg"
But this is not:
print response.attachment
A helper method for expiring a previously-set cookie.
Parameters: key – The key/name of the cookie to expire.
A helper method for setting the HTTP “Set-Cookie” header.
Parameters: - key – The key/name of the cookie.
- value – What to set the cookie to.
- expires – Number of seconds that the cookie should last before being expired. Defaults to None, which makes the cookie last indefinitely.
- http_only – Set the HttpOnly flag.
- secure – Set the Secure flag.
- path – Limit the URI path that the cookie applies to.
- domain – Limit the domain that the cookie applies to.
- get(key)[source]¶
A shortcut for getting a response header.
Parameters: key – The key of the header to get.
- links[source]¶
A helper for setting the “Link” header. To set links, simply do something like:
response.links = { 'http://google.com/meta.rdf': 'meta' }
Note that this is a setter-only property. Reading from it is not valid.
- redirect(path, code=302)[source]¶
A shortcut for setting the response status and HTTP “Location” header appropriately to redirect the requesting client.
Parameters: - path (str) – The location to send the client to.
- code – The status code to set.
- set(key, value)[source]¶
A shortcut for setting a response header.
Parameters: - key – The key of the header to set.
- value – The value of the header.
- status[source]¶
The response status code. This is an instance of StatusCode and can be set using any of the following methods:
response.status = 404 response.status = "404 Not Found" reponse.status.set(404)
Checking a status is as simple as doing any of the following:
response.status == 404 response.status == "404 Not Found"
Engines¶
Gimme makes it very easy to implement adapters to interface with your favorite template engine (I call these adapters “engines”, terminology taken from Express JS).
All that is needed is to subclass of the gimme.engines.BaseEngine (abstract base) class and implement the render() method.
Example:
class SomeEngine(gimme.engines.BaseEngine):
def render(self, template, data):
return fetch_template(template, data)
Now, to use your new engine, simply pass it to your app on instantiation:
app = App(engine=SomeEngine())
- class gimme.engines.Jinja2Engine(template_path='views', environment=None)[source]¶
Provides Jinja2 integration.
Parameters: - template_path – The path, relative the current working directory, that Jinja2 should look for templates.
- environment – A Jinja2 Environment object. Defaults to None. If provided, template_path is ignored.