The agar package contains a number of general purpose utility modules containing classes and functions to help develop with Google App Engine python and webapp2.
The agar.auth module contains classes, functions, and decorators to help secure a webapp2.Requesthandler.
An authenticate function for use with the authentication_required() decorator. Simply aborts the call with a status code of 403.
A decorator to authenticate a webapp2.RequestHandler. The decorator will assign the return value from the authenticate function to the request user attribute (or any re-configured name via the config AUTHENTICATION_PROPERTY), that is passed to the decorated handler. The authenticate function can call webapp2.abort if there was a problem authenticating the call.
Parameters: |
|
---|
A decorator to authenticate a secure request to a webapp2.RequestHandler. Simply calls the authentication_required() decorator with require_https=True.
Parameters: | authenticate – The authentication function passed to the authentication_required() decorator. |
---|
Config settings for the agar.auth library. Settings are under the agar_auth namespace.
The following settings (and defaults) are provided:
agar_auth_AUTHENTICATION_PROPERTY = 'user'
agar_auth_DEFAULT_AUTHENTICATE_FUNCTION = agar.auth.authenticate_abort_403
To override agar.auth settings, define values in the appengine_config.py file in the root of your project.
The property name under which to place the authentication object on the request.
The default authenticate function. It should take a single webapp2.RequestHandler argument, and return a value representing the authentication or call webapp2.abort to short circuit the decorated handler. The type of the returned value can be anything, but it should be a type that your webapp2.RequestHandler expects. The default implementation always calls webapp2.abort with a status code of 403.
Parameters: | handler – The webapp2.RequestHandler object to authenticate. |
---|---|
Returns: | The result of the authentication. |
The agar.config module contains a class to help work with the google.appengine.api.lib_config configuration library.
Configurable constants base class for use with the excellent google.appengine.api.lib_config configuration library.
To use this class, create a subclass that redefines _prefix to the appengine_config prefix you’d like the configs to appear under. Then, simply create class-level properties/functions/default values for each constant.
When instantiating an instance of this class, you can override the default values for that instance by passing in new defaults via the constructor. Of course, if there is an entry in appengine_config.py for your constant, that value will supersede any defined in the class or passed in via the constructor.
Example subclass:
class SampleConfig(Config):
_prefix = 'test'
STRING_CONFIG = 'defaultstring'
Example usage:
>>> config = SampleConfig.get_config()
>>> custom_config = SampleConfig.get_config(STRING_CONFIG='customstring')
Assuming there is no override for test_STRING_CONFIG in appengine_config.py:
>>> config.STRING_CONFIG == 'defaultstring'
True
>>> custom_config.STRING_CONFIG == 'customstring'
True
Assuming appengine_config.py contains the following line:
test_STRING_CONFIG = 'settingstring'
Then:
>>> config.STRING_CONFIG == custom_config.STRING_CONFIG == 'settingstring'
True
The appengine_config prefix that the configs should appear under. Override in subclasses. The default is agar.
Registers and returns the google.appengine.api.lib_config ConfigHandle for the class. Keyword arguments will override default values defined in the Config subclass (but, of course, will still defer to values in the appengine_config.py file).
Parameters: | kwargs – Defaults to use for the config instance. Values in appengine_config.py will still override any values you specify. |
---|---|
Returns: | The google.appengine.api.lib_config ConfigHandle for the class. |
Registers the google.appengine.api.lib_config ConfigHandle and returns its settings as a dict. Keyword arguments will override default values defined in the Config subclass (but, of course, will still defer to values in the appengine_config.py file).
Parameters: | kwargs – Defaults to use for the config instance. Values in appengine_config.py will still override any values you specify. |
---|---|
Returns: | A dict of the configurations. |
The agar.counter module contains classes to help work with scalable counters.
Flush the value of a counter.
Parameters: | name – The name of the counter to flush. |
---|
Returns the value of a counter.
Parameters: | name – The name of the counter. |
---|---|
Returns: | The integer value of the count. |
Increments a counter.
Parameters: |
|
---|
Flushes the value of the counter with the specified name and timestamp to the datastore.
Parameters: |
|
---|
Returns the value of a counter with a specified timestamp.
Parameters: |
|
---|---|
Returns: | The integer value of the count. |
Increments a counter.
Parameters: |
|
---|
Returns the value of a counter with a specified timestamp.
Parameters: |
|
---|---|
Returns: | The integer value of the count. |
Flushes the value of the counter with the specified name and timestamp to the datastore.
Parameters: |
|
---|
Increments a counter.
Parameters: |
|
---|
Returns the value of a counter with a specified timestamp.
Parameters: |
|
---|---|
Returns: | The integer value of the count. |
Flushes the value of the counter with the specified name and timestamp to the datastore.
Parameters: |
|
---|
Increments a counter.
Parameters: |
|
---|
The agar.dates module contains a function to help work with dates.
Create datetime object representing date/time expressed in a string.
Takes a string in the format produced by calling str() on a python datetime object and returns a datetime instance that would produce that string.
Acceptable formats are:
- YYYY-MM-DD HH:MM:SS.ssssss+HH:MM
- YYYY-MM-DD HH:MM:SS.ssssss
- YYYY-MM-DD HH:MM:SS+HH:MM
- YYYY-MM-DD HH:MM:SS
- YYYY-MM-DD
Where ssssss represents fractional seconds. The timezone is optional and may be either positive or negative hours/minutes east of UTC.
Parameters: | s – The string to parse into a datetime. |
---|---|
Returns: | The datetime represented by the given string. |
The agar.django package contains a number of general purpose utility modules containing classes, functions, and decorators to help develop with Google App Engine python and django.
The agar.django.decorators module contains functions and decorators to help validate django forms, to be used to wrap agar.json.JsonRequestHandler methods that accept input.
A decorator that validates input matches with a django form class.
If the form is valid with the given request parameters, the decorator will add the bound form to the request under the form attribute and pass control on to the wrapped handler method.
If the form doesn’t validate, it will return a well-formed JSON response with a status code of 400 including an error dictionary describing the input errors.
Parameters: |
|
---|
The agar.django.forms module contains form classes to help using django forms with a webapp2.Request.
A django form class that holds a reference to the current webapp2.Request.
The form’s webapp2.Request.
A RequestForm that validates all passed parameters are expected by the form.
The agar.django.templates module contains function(s) to render django templates in a manner that is aware of template loaders and dirs configured in the DJANGO_SETTINGS_MODULE
A helper function that renders django templates in a manner that is aware of the loaders and dirs configured in the DJANGO_SETTINGS_MODULE
Parameters: |
|
---|
A helper function that renders a Django template as a string in a manner that is aware of the loaders and dirs configured in the DJANGO_SETTINGS_MODULE.
Parameters: |
|
---|
The agar.env module contains a number of constants to help determine which environment code is running in.
True if running in the dev server, False otherwise.
True if running on a google server and the application ID ends in -int, False otherwise.
True if running on a google server and the application ID does not end in -int, False otherwise.
True if running on a google server, False otherwise.
The agar.image module contains classes to help work with images stored in the Blobstore.
A model class that helps create and work with images stored in the Blobstore. Please note that you should never call the constructor for this class directly when creating an image. Instead, use the create() method.
Create an Image. Use this class method rather than creating an image with the constructor. You must provide one of the following parameters blob_info, data, or url to specify the image data to use.
Parameters: |
|
---|---|
Returns: | An instance of the Image class. |
Called to create a new entity. The default implementation simply creates the entity with the default constructor and calls put(). This method allows the class to be mixed-in with agar.models.NamedModel.
Parameters: | kwargs – Parameters to be passed to the constructor. |
---|
The create timestamp.
Delete the image and its attached Blobstore storage.
Parameters: | kwargs – Parameters to be passed to parent classes delete() method. |
---|
The format of the image (see Image.format for possible values). If there is no image data, this will be None.
Returns the serving URL for the image. It works just like the Image.get_serving_url function, but adds caching. The cache timeout is controlled by the SERVING_URL_TIMEOUT setting.
Parameters: |
|
---|---|
Returns: | The serving URL for the image (see Image.get_serving_url for more detailed information). |
The height of the image in pixels (see Image.height for more documentation). If there is no image data, this will be None.
The raw image data as returned by a BlobReader. If there is no image data, this will be None.
The last modified timestamp.
The original URL that the image data was fetched from, if applicable.
The width of the image in pixels (see Image.width for more documentation). If there is no image data, this will be None.
Config settings for the agar.image library. Settings are under the agar_image namespace.
The following settings (and defaults) are provided:
agar_image_SERVING_URL_TIMEOUT = 60*60
agar_image_SERVING_URL_LOOKUP_TRIES = 3
agar_image_VALID_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif']
To override agar.image settings, define values in the appengine_config.py file in the root of your project.
How many times to try to download an image from a URL (Default: 3).
How long (in seconds) to cache the image serving URL (Default: 60*60 or one hour).
Valid image mime types (Default: ['image/jpeg', 'image/png', 'image/gif']).
A webapp2.RequestHandler implementation to help with json web service handlers, including error handling.
The webapp2.RequestHandler exception handler. Sets the webapp2.Response with appropriate settings.
Parameters: |
|
---|
Fills in the webapp2.Response with the contents of the passed model or query serialized using the restler library.
Parameters: |
|
---|---|
Returns: | The serialized text to be used as the HTTP response data. |
A JsonRequestHandler class to help with page_size and cursor parsing and logic.
Fetches a page of the passed query using the page_size and the cursor request parameter.
Parameters: | query – The Query to fetch from. |
---|---|
Returns: | A two-tuple containing results of the paged fetch and the next page’s cursor if there’s more results. |
The requested page_size constrained between 1 and the configuration value agar_json_MAX_PAGE_SIZE. If page_size isn’t passed in, it will default to the configuration value agar_json_DEFAULT_PAGE_SIZE.
Returns: | The requested page size for fetching. |
---|
A MultiPageHandler to help with Cross-Origin Resource sharing .
The agar.models module contains classes to help working with Model.
A base (or mix-in) Model subclass to create an entity with a key_name (either passed in or generated automatically).
This base model has a classmethod for automatically assigning a new uuid for its key_name on creation of a new entity.
Creates and persists an entity by (optionally) generating and setting a key_name. A key_name will be generated or may be provided as a keyword arg. If a generated key_name is already in use, a new one will be generated. If, after the 3rd attempt the key_name is still not unique, a agar.models.DuplicateKeyError will be raised. This exception will also be raised if the argument key_name is not None and not unique.
Parameters: |
|
---|---|
Returns: | The newly created and persisted NamedModel. |
Examples:
person = Person.create_new_entity()
person_with_keyname = Person.create_new_entity(key_name='bob')
Creates a (hopefully) unique string to be used as an identifier. The default implementation uses a uuid4 hex value.
Returns: | A unique string to be used as an identifier. |
---|
The entity’s key().name() unicode value if available, otherwise None.
The NamedModel tried to create an instance with a key_name that is already in use.
There was an exception working with a Model while processing a agar.json.JsonRequestHandler.
The agar.sessions module contains classes to assist with creating webapp2.RequestHandler s.
A webapp2.RequestHandler implementation that provides access to a session via the session attribute..
Dispatches the request after grabbing the session_store and providing access to the current webapp2.Request ‘s session.
This will first check if there’s a handler_method defined in the matched route, and if not it’ll use the method correspondent to the request method (get(), post() etc).
Returns a session using the default cookie key.
A webapp2_extras.sessions.SessionStore implementation that uses Webapp2ExtrasSessionsConfig instead of the built-in webapp2 config library.
Config settings for the webapp2_extras.sessions library. Settings are under the webapp2_extras_sessions namespace.
The following settings (and defaults) are provided:
cookie_args = {
'max_age': None,
'domain': None,
'secure': None,
'httponly': False,
'path': '/'
}
secret_key = None,
cookie_name = 'session'
session_max_age = None
backends = {
'datastore': 'webapp2_extras.appengine.sessions_ndb.DatastoreSessionFactory',
'memcache': 'webapp2_extras.appengine.sessions_memcache.MemcacheSessionFactory',
'securecookie': 'webapp2_extras.sessions.SecureCookieSessionFactory'
}
To override webapp2_extras.sessions settings, define values in the appengine_config.py file in the root of your project.
Registers the google.appengine.api.lib_config ConfigHandle and returns its settings as a webapp2 configuration dict with the webapp2_extras.sessions configurations under the key webap2_extras.sessions. Keyword arguments will override default values defined in the Config subclass (but, of course, will still defer to values in the appengine_config.py file).
Parameters: |
|
---|---|
Returns: | A dict of the configurations. |
The google.appengine.api.lib_config ConfigHandle for webapp2_extras_sessions settings.
Returns a URL matching given the route name with its parameters.
See uri_for() for more detailed parameter information.
For example:
{% uri_for route_name arg1,arg2,name1=value1 %}
{% uri_for get_client id=client.id %}
{% uri_for get_client id=client.id,_full=True %}
Returns whether the code is running on a production server. See on_production_server() for more information.
Returns: | True if running on a production server, False otherwise. |
---|
Inserts a Google Account logout url.
The agar.test package contains helpers for unit testing your application.
A base class for App Engine unit tests that sets up API proxy stubs for all available services using testbed and clears them between each test run.
Note: the images stub is only set up if PIL is found.
To use, simply inherit from BaseTest:
import agar
from models import MyModel
class MyTestCase(agar.test.BaseTest):
def test_datastore(self):
model = MyModel(foo='foo')
model.put()
# will always be true because the datastore is cleared
# between test method runs.
self.assertEqual(1, MyModel.all().count())
BaseTest is designed to be mostly API-compatable with gaetestbed‘s assertions. However, unlike gaetestbed, the assertions are split into only two classes: BaseTest and WebTest.
Assert that no email was sent with the specified criteria.
Parameters: |
|
---|
Assert that at least one email was sent with the specified criteria.
Note that App Engine does not allow emails to be sent from non-administrative users of the application. This method cannot check for that.
Examples:
mail.send_mail(to='test@example.com',
subject='hello world',
sender='foobar@example.com',
body='I can has email?')
self.assertEmailSent()
self.assertEmailSent(to='test@example.com')
# this will fail
self.assertEmailSent(to='foobar@example.com')
Parameters: |
|
---|
Assert that iterable is of length 0. Equivalent to self.assertLength(0, iterable).
Assert that iterable is of length expected.
NOTE: This assertion uses the standard xUnit (expected, actual) order for parameters. However, this is the reverse of gaetestbed.
Parameters: |
|
---|
Asserts that the memcache API has had hits successful lookups.
Parameters: | hits – number of memcache hits |
---|
Asserts that the memcache API has items key-value pairs.
Parameters: | items – number of items in memcache |
---|
Search for Task objects matching the given criteria and assert that there are n tasks.
Example:
deferred.defer(some_task, _name='some_task')
self.assertTasksInQueue(n=1, name='some_task')
Parameters: |
|
---|
Clear the Data Store of all its data.
This method can be used inside your tests to clear the Data Store mid-test.
For example:
import unittest
from agar.test import BaseTest
class MyTestCase(BaseTest):
def test_clear_datastore(self):
# Add something to the Data Store
models.MyModel(field="value").put()
self.assertLength(models.MyModel.all(), 1)
# And then empty the Data Store
self.clear_datastore()
self.assertLength(models.MyModel.all(), 0)
Return a list of email messages matching the given criteria.
Parameters: |
|
---|
Returns a list of Task objects with the specified criteria.
Parameters: |
|
---|
Log in a User with the given email address. This will cause users.get_current_user to return a User with the same email address and user_id as if it was entered into the SDK’s log in prompt.
MockUrlfetchTest replaces the urlfetch API stub with a mocked version that does not make real HTTP requests.
To use it, inherit from MockUrlfetchTest instead of BaseTest, then register HTTP responses in your setUp method, or individual test case methods.
If any of the code under test results in urlfetch call to an unregistered URL, it will raise an exception.
Example:
class MyHTTPTest(MockUrlfetchTest):
def setUp(self):
super(MyHTTPTest, self).setUp()
self.set_response("http://www.google.com/blah", content="foobar", status_code=404)
def test_get_google(self):
result = urlfetch.fetch("http://www.google.com/blah")
self.assertEqual(404, result.status_code)
self.assertEqual("foobar", result.content)
def test_this_will_fail(self):
result = urlfetch.fetch("http://www.example.com/")
Register an HTTP response for url with body containing content.
NOTE: MockUrlfetchTest does not follow redirects at this time.
Examples:
# Will cause a 200 OK response with no body for all HTTP methods:
self.set_response("http://example.com")
# Will cause a 404 Not Found for GET requests with 'gone fishing' as the body:
self.set_response("http://example.com/404ed", content='gone fishing', status_code=404)
# Will cause a 303 See Other for POST requests with a Location header and no body:
self.set_response("http://example.com/posts", status_code=303, headers={'Location': 'http://example.com/posts/123'})
# Will cause a DownloadError to be raised when the URL is requested:
from google.appengine.api import urlfetch
self.set_response("http://example.com/boom", content=urlfetch.DownloadError("Something Failed"))
Parameters: |
|
---|
A base class for testing web requests. Provides a wrapper around the WebTest package that is mostly compatable with gaetestbed‘s.
To use, inherit from WebTest and define a class-level variable called APPLICATION that is set to the WSGI application under test.
WebTest is usually used in conjuction with BaseTest to set up the App Engine API proxy stubs.
Example:
from agar.test import BaseTest, WebTest
import my_app
class TestMyApp(BaseTest, WebTest):
APPLICATION = my_app.application
def test_get_home_page(self):
response = self.get("/")
self.assertOK(response)
Assert that response was 400 Bad Request.
Assert that response was 403 Forbidden.
Assert that response was 404 Not Found.
Assert that response was 200 OK.
Assert that response was a 302 redirect.
Parameters: | to – an absolute or relative URL that the redirect must match. |
---|
Assert that response was 401 Unauthorized.
Parameters: | challenge – assert that the WWW-Authenticate header matches this value, if provided |
---|
The agar.url module contains classes to help working with application-wide URLs.
A wrapper around the webapp2.uri_for function that will search all applications defined in the agar_url_APPLICATIONS configuration.
Parameters: |
|
---|---|
Returns: | An absolute or relative URI. |
Config settings for the agar.url library. Settings are under the agar_url namespace.
The following settings (and defaults) are provided:
agar_url_DEBUG = False
agar_url_PRODUCTION_DOMAIN = ''
agar_url_APPLICATIONS = ['main']
To override agar.url settings, define values in the appengine_config.py file in the root of your project.