### Install Appier Package (Bash)
Source: https://github.com/hivesolutions/appier/blob/master/CLAUDE.md
Provides commands to install the Appier package in development mode using pip and to install it from PyPI.
```Bash
pip install -e .
pip install appier
```
--------------------------------
### Install Dependencies and Run Tests (Bash)
Source: https://github.com/hivesolutions/appier/blob/master/CLAUDE.md
Installs project dependencies using pip and executes tests with pytest. It configures environment variables for testing specific adapters and HTTP backends.
```Bash
pip install -r requirements.txt
pip install -r extra.txt
pip install pytest netius
ADAPTER=tiny HTTPBIN=httpbin.bemisc.com pytest
```
--------------------------------
### Bash: Install and Run Appier
Source: https://github.com/hivesolutions/appier/blob/master/README.md
Commands to install the Appier framework using pip and run a Python application. This covers the basic setup and execution of an Appier web application.
```Bash
pip install appier
python hello.py
```
--------------------------------
### Appier Controller for Data Retrieval (Python)
Source: https://github.com/hivesolutions/appier/blob/master/CLAUDE.md
Illustrates how to create a controller in Appier that inherits from appier.Controller. This example defines a route to fetch user data using the previously defined User model.
```Python
class UserController(appier.Controller):
@appier.route("/users", "GET")
def list(self):
return User.find()
```
--------------------------------
### Format Code with Black (Bash)
Source: https://github.com/hivesolutions/appier/blob/master/CLAUDE.md
Installs the Black code formatter and applies it to the entire project to ensure consistent code style.
```Bash
pip install black
black .
```
--------------------------------
### Starting an Appier App
Source: https://github.com/hivesolutions/appier/blob/master/doc/app.md
Provides the code to instantiate and run an Appier application. This is the standard method to launch the application's event loop and make it accessible.
```python
HelloApp().serve()
```
--------------------------------
### Basic Appier Application Structure (Python)
Source: https://github.com/hivesolutions/appier/blob/master/CLAUDE.md
Demonstrates the basic structure of an Appier application by defining a simple class that inherits from appier.App and includes a route for a 'Hello World' response.
```Python
import appier
class MyApp(appier.App):
@appier.route("/", "GET")
def hello(self):
return "Hello World"
```
--------------------------------
### Appier Controller Example (Python)
Source: https://github.com/hivesolutions/appier/blob/master/doc/structure.md
Demonstrates a basic Appier controller. This 'CatController' defines a 'list' method that handles GET requests to '/cats'. It retrieves 'Cat' models, processes them, and renders a template.
```Python
import appier
import models
class CatController(appier.Controller):
@appier.route("/cats", "GET")
def list(self):
cats = models.Cat.find()
for cat in cats: cat.meow()
return self.template(
"cat/list.html.tpl",
cats = cats
)
```
--------------------------------
### Appier Configuration Example (JSON)
Source: https://github.com/hivesolutions/appier/blob/master/doc/structure.md
An example of an Appier configuration file named 'appier.json'. This JSON file contains settings that can be accessed during the application's runtime, such as a base URL.
```JSON
{
"BASE_URL" : "http://www.hive.pt"
}
```
--------------------------------
### Install Appier with pip
Source: https://github.com/hivesolutions/appier/blob/master/README.rst
This command installs the Appier Python web framework using pip, the Python package installer. Ensure you have pip installed and configured correctly.
```shell
pip install appier
```
--------------------------------
### Appier App Example (Python)
Source: https://github.com/hivesolutions/appier/blob/master/doc/structure.md
Demonstrates the basic structure of an Appier application. It defines a simple 'Hello World' app with a root route that returns a string. The app is then instantiated and served.
```Python
import appier
class HelloApp(appier.App):
@appier.route("/", "GET")
def hello(self):
return "Hello World"
HelloApp().serve()
```
--------------------------------
### Appier Handling Multiple HTTP Methods
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Demonstrates how a single handler method in Appier can be configured to respond to multiple HTTP methods for a given route. This example handles both GET and POST requests for '/cats/garfield'.
```Python
@appier.route("/cats/garfield", ("GET", "POST"))
def hello(self):
return "hello from /cats/garfield"
```
--------------------------------
### Appier Template Example (Jinja2)
Source: https://github.com/hivesolutions/appier/blob/master/doc/structure.md
An example of a Jinja2 template used within an Appier project. It iterates over a list of 'cats' and displays their names in an HTML table.
```HTML
{% for cat in cats %}
| {{ cat.name }} |
{% endfor %}
```
--------------------------------
### Appier Handling Longer URL Paths
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Shows how to define routes for more specific URL paths in Appier. This example maps a GET request to '/cats/garfield' to a handler method.
```Python
@appier.route("/cats/garfield", "GET")
def hello(self):
return "hello from garfield"
```
--------------------------------
### Format Python Code with Black
Source: https://github.com/hivesolutions/appier/blob/master/AGENTS.md
This snippet demonstrates how to install and use the 'black' formatter to ensure consistent Python code style. It's a prerequisite for committing code.
```bash
pip install black
black .
```
--------------------------------
### Appier Model Definition (Python)
Source: https://github.com/hivesolutions/appier/blob/master/CLAUDE.md
Shows how to define a data model in Appier by creating a class that inherits from appier.Model and defining fields for attributes like 'name' and 'email'.
```Python
class User(appier.Model):
name = appier.field()
email = appier.field()
```
--------------------------------
### Python: Basic Hello World App
Source: https://github.com/hivesolutions/appier/blob/master/README.md
A simple 'Hello World' application using the Appier framework. This example demonstrates the basic structure of an Appier application, including defining a route and a handler function.
```Python
import appier
class HelloApp(appier.App):
@appier.route("/", "GET")
def hello(self):
return "Hello World"
HelloApp().serve()
```
--------------------------------
### Run Full Test Suite with Pytest
Source: https://github.com/hivesolutions/appier/blob/master/AGENTS.md
This sequence of commands installs necessary dependencies and runs the project's test suite using 'pytest'. It includes setting an environment variable 'ADAPTER' and 'HTTPBIN'.
```bash
pip install -r requirements.txt
pip install -r extra.txt
pip install pytest netius
ADAPTER=tiny HTTPBIN=httpbin.bemisc.com pytest
```
--------------------------------
### Python: Async Hello World App
Source: https://github.com/hivesolutions/appier/blob/master/README.md
An asynchronous 'Hello World' application using Appier, compatible with Python 3.5+ and ASGI servers. This example showcases the use of `async` and `await` for non-blocking request handling.
```Python
import appier
class HelloApp(appier.App):
@appier.route("/", "GET")
async def hello(self):
await self.send("Hello World")
HelloApp().serve()
```
--------------------------------
### Appier Basic Routing
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Demonstrates setting up a basic web application in Appier and handling requests to the root URL ('/'). It uses the @appier.route decorator to map the GET request to the hello method.
```Python
import appier
class HelloApp(appier.App):
@appier.route("/", "GET")
def hello(self):
return "hello from /"
HelloApp().serve()
```
--------------------------------
### Basic Appier Web App
Source: https://github.com/hivesolutions/appier/blob/master/README.rst
This Python code demonstrates a minimal web application using the Appier framework. It defines a simple app that responds to GET requests at the root URL with 'Hello World'. The app is then served.
```Python
import appier
class HelloApp(appier.App):
@appier.route("/", "GET")
def hello(self):
return "Hello World"
HelloApp().serve()
```
--------------------------------
### Generate Relative URL for Handler in Appier
Source: https://github.com/hivesolutions/appier/blob/master/doc/templates.md
Explains how to create a relative URL to a controller handler using the `url_for` method in Appier. This example links to the `list` handler in `CatController`.
```HTML
List Cats
```
--------------------------------
### Define Model Validations in Appier
Source: https://github.com/hivesolutions/appier/blob/master/doc/models.md
Demonstrates how to define validation rules for a model using the `validate` class method in Appier. It includes examples of `not_null`, `not_empty`, and `gte` validators.
```Python
class Cat(appier.Model):
name = appier.field(
type = unicode
)
age = appier.field(
type = int
)
@classmethod
def validate(cls):
return super(Cat, cls).validate() + [
appier.not_null("name"),
appier.not_empty("name"),
appier.gte("age", 5)
]
```
--------------------------------
### Python Appier Controller for Listing Cats
Source: https://github.com/hivesolutions/appier/blob/master/doc/controllers.md
Defines a GET route '/cats' in an Appier controller to list all cats. It retrieves cat entities from the data source, invokes a 'meow' method on each, and renders a 'cat/list.html.tpl' template with the cat data.
```Python
import appier
import models
class CatController(appier.Controller):
@appier.route("/cats", "GET")
def list(self):
cats = models.Cat.find()
for cat in cats: cat.meow()
return self.template(
"cat/list.html.tpl",
cats = cats
)
```
--------------------------------
### Appier Handling POST Requests
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Illustrates how to handle POST requests to a specific URL path using the @appier.route decorator in Appier. This example maps POST requests to '/cats/garfield'.
```Python
@appier.route("/cats/garfield", "POST")
def hello(self):
return "hello from /cats/garfield"
```
--------------------------------
### Appier Capturing URL Parameters
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Explains how to capture dynamic parts of a URL path as parameters in Appier handler methods. The example uses '' in the route to capture the name and pass it to the handler.
```Python
@appier.route("/cats/", "GET")
def hello(self, name):
return "hello from %s" % name
```
--------------------------------
### Delete a Cat Instance
Source: https://github.com/hivesolutions/appier/blob/master/doc/models.md
This Python code provides a simple example of how to delete a `Cat` instance from the database by calling the `delete()` method on the object.
```Python
cat.delete()
```
--------------------------------
### Appier Custom Exception Handler
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Illustrates how to define a custom handler for specific unhandled exceptions in Appier. This example catches `appier.NotFoundError` and returns a custom message.
```Python
@appier.exception_handler(appier.NotFoundError)
def not_found(self, error):
return "The object you requested was not found"
```
--------------------------------
### Appier Handling Multiple URLs
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Shows how to associate multiple URL paths with a single handler method in Appier using multiple @appier.route decorators. This example maps both '/cats/garfield' and '/cats/felix' to the same handler.
```Python
@appier.route("/cats/garfield", "GET")
@appier.route("/cats/felix", "GET")
def hello(self):
return "hello from garfield or felix (not sure which)"
```
--------------------------------
### Appier Retrieving URL/Form Parameters
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Shows how to retrieve parameters from the URL query string or form data in Appier using the `self.field()` method. This example retrieves a 'name' parameter.
```Python
@appier.route("/cats", ("GET", "POST"))
def hello(self):
name = self.field("name")
return "hello from %s" % name
```
--------------------------------
### Access Static Resource URL in Appier
Source: https://github.com/hivesolutions/appier/blob/master/doc/templates.md
Shows how to generate a URL for static resources (like images) using `url_for('static', ...)` in Appier. This example links to an image file located in the `static` directory.
```HTML
```
--------------------------------
### Python Appier Controller for Redirecting Cat Show
Source: https://github.com/hivesolutions/appier/blob/master/doc/controllers.md
Defines a GET route '/cats/' in an Appier controller that handles a specific cat's ID. Instead of returning data, it redirects the user to the 'animal.show' URL, passing the cat's ID.
```Python
@appier.route("/cats/", "GET")
def show(self, id):
return self.redirect(
self.url_for("animal.show", id = id)
)
```
--------------------------------
### Appier Model Definition (Python)
Source: https://github.com/hivesolutions/appier/blob/master/doc/structure.md
Illustrates how to define a data model in Appier. This example shows a 'Cat' model inheriting from 'appier.Model' with an 'id' field configured with specific properties like type, indexing, and auto-increment.
```Python
import appier
class Cat(appier.Model):
id = appier.field(
type = int,
index = True,
increment = True
)
```
--------------------------------
### Generate Absolute URL in HTML
Source: https://github.com/hivesolutions/appier/blob/master/doc/email.md
Provides an HTML example demonstrating how to generate an absolute URL for a link using the `url_for` function with the `absolute=True` argument. This ensures the URL is prefixed with the `BASE_URL` configuration.
```HTML
The App
```
--------------------------------
### Appier Type Casting URL Parameters
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Demonstrates Appier's ability to automatically cast captured URL parameters to specified types. This example casts the 'number' parameter to an integer.
```Python
@appier.route("/numbers/", "GET")
def hello(self, number):
return "this is number %d" % number
```
--------------------------------
### Appier Custom Error Handler (404)
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Shows how to define a custom handler for specific HTTP error codes in Appier. This example provides a custom response for a 404 Not Found error.
```Python
@appier.error_handler(404)
def not_found_code(self, error):
return "404 - The page you requested was not found"
```
--------------------------------
### Managing User Tokens in Session
Source: https://github.com/hivesolutions/appier/blob/master/doc/access_control.md
These Python examples show how to manage user access tokens within the session object. Tokens are added to `self.session["tokens"]` upon login and removed upon logout.
```Python
self.session["tokens"] = ["base"]
# To log out:
del self.session["tokens"]
```
```Python
self.session["tokens"] = ["base", "admin"]
```
```Python
self.session["tokens"] = ["*"]
```
--------------------------------
### Basic Appier App Structure
Source: https://github.com/hivesolutions/appier/blob/master/doc/app.md
Demonstrates the fundamental structure of an Appier application. It shows how to define a simple 'Hello World' route using the @appier.route decorator and how to create a class that inherits from appier.App.
```python
import appier
class HelloApp(appier.App):
@appier.route("/", "GET")
def hello(self):
return "Hello World"
```
--------------------------------
### Configuring Appier App Initialization
Source: https://github.com/hivesolutions/appier/blob/master/doc/app.md
Illustrates how to configure an Appier application by defining its __init__ method. This allows for setting application-specific parameters like the application name during instantiation.
```python
class HelloApp(appier.App):
def __init__(self, *args, **kwargs):
appier.App.__init__(
self,
name = "app_name",
*args, **kwargs
)
```
--------------------------------
### Python - Advanced Cat Retrieval
Source: https://github.com/hivesolutions/appier/blob/master/doc/models.md
Demonstrates retrieving cats that are not named 'Garfield' using the '$ne' operator with get, count, and find methods.
```Python
not_garfield = Cat.get(name = {"$ne" : "Garfield"})
number_not_garfields = Cat.count(name = {"$ne" : "Garfield"})
number_garfields = Cat.find(name = {"$ne" : "Garfield"})
```
--------------------------------
### Bash: Run Async App with Uvicorn
Source: https://github.com/hivesolutions/appier/blob/master/README.md
Instructions to run an asynchronous Appier application using the Uvicorn server. This requires setting the SERVER environment variable to 'uvicorn' before executing the Python script.
```Bash
SERVER=uvicorn python hello.py
```
--------------------------------
### Render Basic Template in Appier
Source: https://github.com/hivesolutions/appier/blob/master/doc/templates.md
Demonstrates how to render a Jinja2 template using the `template` method in an Appier controller. The `list` handler in `CatController` renders 'cat/list.html.tpl'.
```Python
import appier
class CatController(appier.Controller):
@appier.route("/cats", "GET")
def list(self):
return self.template(
"cat/list.html.tpl"
)
```
--------------------------------
### Access Reserved Session Variable in Jinja2
Source: https://github.com/hivesolutions/appier/blob/master/doc/templates.md
Shows how to access reserved variables injected into Jinja2 templates by Appier. This example displays the logged-in user's email from the `session` object.
```HTML
Logged in as {{ session.email }}
```
--------------------------------
### Listen to Post Create Persistence Event
Source: https://github.com/hivesolutions/appier/blob/master/doc/events.md
This Python code demonstrates how to listen to the 'post_create' persistence event for a `Cat` model using `bind_g`. The `handle_cat_post_create` method is executed after a new `Cat` instance has been successfully created and saved.
```python
@classmethod
def setup(cls):
super(MeowTracker, cls).setup()
cat.Cat.bind_g("post_create", cls.handle_cat_post_create)
@classmethod
def handle_cat_post_create(cls, ctx):
print("Cat '%s' was born" % ctx.name)
```
--------------------------------
### Get Current Location URL in Appier
Source: https://github.com/hivesolutions/appier/blob/master/doc/templates.md
Demonstrates how to retrieve the current relative or absolute URL path using the `location` variable within `url_for` in Appier. This is useful for creating self-referential links.
```HTML
Loop Link
```
--------------------------------
### Configure TinyDB Settings
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Sets up the configuration for TinyDB, a lightweight document-oriented database. It includes options for the database file path (TINY_PATH) and the storage engine (TINY_STORAGE).
```Python
import os
TINY_PATH = os.environ.get('TINY_PATH', 'db.json')
TINY_STORAGE = os.environ.get('TINY_STORAGE', 'json')
```
--------------------------------
### Configure File Session Persistence (Python)
Source: https://github.com/hivesolutions/appier/blob/master/doc/sessions.md
Demonstrates how to configure the Appier application to use FileSession for persisting session data. This involves passing the session_c keyword argument during app initialization.
```Python
import appier
class HelloApp(appier.App):
def __init__(self):
appier.App.__init__(
self,
session_c = appier.session.FileSession
)
HelloApp().serve()
```
--------------------------------
### Appier Server Configuration
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Defines the server environment for the Appier application. Includes settings for the server type, host address, port, and backlog for pending connections.
```Python
SERVER = "legacy" # Options: legacy, netius, waitress, tornado, cherrypi
HOST = "127.0.0.1" # Address to bind the server to
PORT = 8080 # Port for the server to listen on
BACKLOG = socket.SOMAXCONN # Max pending connections
```
--------------------------------
### Appier HTTP Client Configuration
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Sets up the HTTP client used for making external requests. Includes options for the client type, connection reuse, and request timeout.
```Python
HTTP_CLIENT = "netius" # Options: legacy, netius, requests
HTTP_REUSE = True # Reuse HTTP client connections
HTTP_TIMEOUT = 60 # Timeout in seconds for HTTP requests
```
--------------------------------
### Running an Appier App (Shell)
Source: https://github.com/hivesolutions/appier/blob/master/doc/structure.md
Shows the command to execute a Python script that serves an Appier application. This is typically run from the project's root directory.
```Shell
python hello.py
```
--------------------------------
### Appier Configuration via Environment Variable
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Demonstrates how to override configuration settings defined in a file by using environment variables. This is useful for managing different configurations across various deployment environments.
```bash
LEVEL=WARNING python hello.py
```
--------------------------------
### Send Email with Default Configuration (Python)
Source: https://github.com/hivesolutions/appier/blob/master/doc/email.md
Demonstrates sending an email using the `email` method with default configuration settings. The template, subject, sender, and receivers are specified.
```Python
self.email(
"template.html.tpl",
subject = "Test email",
sender = "Sender Name ",
subject = "Test email",
sender = "sender@email.com",
receivers = ["receiver@email.com"]
)
```
--------------------------------
### Enable Database Query Debugging
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Controls the display of extra debug information related to database queries. When SHOW_QUERIES is set to True, detailed query information will be logged.
```Python
import os
SHOW_QUERIES = os.environ.get('SHOW_QUERIES', 'False').lower() == 'true'
```
--------------------------------
### Create Cat Instance with Automatic Form Data Mapping
Source: https://github.com/hivesolutions/appier/blob/master/doc/models.md
This Python snippet shows how to create a new `Cat` instance using `Cat.new()`, which facilitates automatic mapping of form data to model attributes. It also demonstrates how to apply form data to an existing `cat` object using the `apply()` method.
```Python
cat = Cat.new()
cat.save()
# Applying form data to an existing cat
cat.apply()
```
--------------------------------
### Appier Parameter Default Values and Casting
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Illustrates how to specify default values and custom casting functions when retrieving parameters using `self.field()` in Appier. This example retrieves an integer 'number' with a default of 5.
```Python
@appier.route("/numbers", ("GET", "POST"))
def hello(self):
number = self.field("number", 5, cast = int)
return "this is number %d" % number
```
--------------------------------
### Configure Email Settings
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Sets up email functionality using SMTP. Requires connection details like URL, host, port, username, password, and TLS settings. Optionally, a HELO host and email locale can be specified.
```python
SMTP_URL = "smtps://username:password@host.com:25"
SMTP_HOST = "host.com"
SMTP_PORT = 25
SMTP_USER = "username"
SMTP_PASSWORD = "password"
SMTP_STARTTLS = True
SMTP_HELO_HOST = "client.com"
EMAIL_LOCALE = "en_US"
```
--------------------------------
### Appier Application Settings
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Provides application-specific settings such as the base URL for resolving relative URLs, a secret key for cryptographic operations, and a list of parts for dynamic loading.
```Python
BASE_URL = "http://localhost:8080" # Base URL for absolute URL generation
SECRET = None # Secret key for cryptographic operations
PARTS = [] # List of Appier Parts to load dynamically
```
--------------------------------
### Appier Configuration File
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Defines application settings using a JSON file, typically named `appier.json`. This file serves as a central point for variables that dictate the app's platform and behavior.
```json
{
"LEVEL": "INFO"
}
```
--------------------------------
### Retrieve Appier Configuration Value with Default
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Illustrates how to provide a default value when retrieving configuration settings using `appier.conf()`. This ensures the application can still function even if a specific setting is not provided.
```python
level = appier.conf("LEVEL", "INFO")
```
--------------------------------
### Create and Save a New Cat Instance
Source: https://github.com/hivesolutions/appier/blob/master/doc/models.md
This Python code illustrates the process of creating a new `Cat` object, setting its `name` attribute, and persisting it to the database using the `save()` method. The `id` attribute is automatically managed due to the `increment` flag in the model definition.
```Python
cat = Cat()
cat.name = "Garfield"
cat.save()
```
--------------------------------
### Listen to Global Cat Event
Source: https://github.com/hivesolutions/appier/blob/master/doc/events.md
This Python code shows how to set up a global listener for the 'cat_meowed' event using `bind_g`. The `MeowTracker` model's `handle_cat_mehowed` class method will be invoked whenever a `Cat` triggers this event.
```python
import cat
class MeowTracker(appier.Model):
@classmethod
def setup(cls):
super(MeowTracker, cls).setup()
cat.Cat.bind_g("cat_meowed", cls.handle_cat_mehowed)
@classmethod
def handle_cat_mehowed(cls, ctx):
print("Cat '%s' mehowed" % ctx.name)
```
--------------------------------
### Enable File Logging via Environment Variable
Source: https://github.com/hivesolutions/appier/blob/master/doc/logging.md
Enables logging to a file by setting the FILE_LOG environment variable to 1 before executing the Python script.
```Bash
FILE_LOG=1 python hello.py
```
--------------------------------
### Send Email with Explicit Configuration (Python)
Source: https://github.com/hivesolutions/appier/blob/master/doc/email.md
Shows how to send an email by providing SMTP configuration parameters directly to the `email` method, overriding global settings. This includes host, port, username, password, and TLS settings.
```Python
self.email(
"template.html.tpl",
subject = "Test email",
sender = "Sender Name ",
receivers = ["receiver@hive.pt"],
host = "hostname.com",
port = 25,
username = "username",
password = "password"
stls = True
)
```
--------------------------------
### Configure MongoDB Connection
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Sets up the connection to a MongoDB database using environment variables. It supports different URL formats like MONGOHQ_URL, MONGOLAB_URI, and MONGO_URL. The MONGO_DB variable specifies the default database name.
```Python
import os
MONGO_URL = os.environ.get('MONGOHQ_URL') or os.environ.get('MONGOLAB_URI') or os.environ.get('MONGO_URL') or 'mongodb://localhost'
MONGO_DB = os.environ.get('MONGO_DB', None)
```
--------------------------------
### Configure Preferences Settings
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Specifies the preferences manager and its storage location. Similar to cache, it supports various backends like file, memory, or Redis. For file-based preferences, a file path is needed for storage.
```python
PREFERENCES = "file"
PREFERENCES_PATH = "/etc/appier/prefs.db"
```
--------------------------------
### Appier Host Rewriting Configuration
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Configures host rewriting rules for incoming requests. If FORCE_HOST is set and the request host does not match, a rewrite will occur.
```Python
FORCE_HOST = None # Rewrite request if host header does not match this value
```
--------------------------------
### Referencing Static Files in Templates (HTML)
Source: https://github.com/hivesolutions/appier/blob/master/doc/structure.md
Shows how to reference a JavaScript file located in the 'static/js/' directory from an HTML template using Appier's 'url_for' function.
```HTML
```
--------------------------------
### Configure Redis Connection
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Configures the connection to a Redis server using environment variables. It supports REDISTOGO_URL and REDIS_URL for connection strings and REDIS_POOL to enable connection pooling.
```Python
import os
REDIS_URL = os.environ.get('REDISTOGO_URL') or os.environ.get('REDIS_URL') or 'redis://localhost'
REDIS_POOL = os.environ.get('REDIS_POOL', 'True').lower() == 'true'
```
--------------------------------
### Listen to Instance-Specific Cat Event
Source: https://github.com/hivesolutions/appier/blob/master/doc/events.md
This Python snippet illustrates how to listen to an event ('cat_meowed') on a specific instance of the `MeowTracker` model using the `bind` method. The `handle_cat_mehowed` method within the instance will be called when the event occurs.
```python
class MeowTracker(appier.Model):
def listen(self):
self.bind("cat_meowed", self.handle_cat_mehowed)
def handle_cat_mehowed(self, ctx):
print("Cat '%s' mehowed" % ctx.name)
```
--------------------------------
### Debug Configuration
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Enables extended file path inclusion in traceback lines and specifies whether to use the Git engine for traceback debugging.
```Python
EXTENDED_PATH = True
EXTENDED_GIT = False
```
--------------------------------
### Bus Configuration
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Configures the bus manager for creating federated environments and orchestration using an event-driven approach. It also defines a global name for diffusion scopes.
```Python
BUS = "memory" # or "redis"
BUS_NAME = "global"
```
--------------------------------
### Retrieve Appier Configuration Value
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Shows how to access configuration values within the application logic using the `appier.conf()` function. This allows dynamic adjustment of application behavior based on external settings.
```python
level = appier.conf("LEVEL")
```
--------------------------------
### Configure Logging Settings
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Manages application logging verbosity and output. Supports file, stream, memory, and remote syslog logging. Custom logging formats and extra debug information can be enabled.
```python
LEVEL = "INFO"
FILE_LOG = True
STREAM_LOG = True
MEMORY_LOG = True
SYSLOG_HOST = "syslog.server.com"
SYSLOG_PORT = 514
SYSLOG_PROTO = "udp"
LOGGING = ["complex"]
LOGGING_EXTRA = True
LOGGING_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
```
--------------------------------
### Session Management Configuration
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Defines the session manager to be used, supporting file, memory, or Redis-based sessions. It also allows specifying a custom file path for session storage.
```Python
SESSION = "file" # or "memory", "redis", "client"
SESSION_FILE_PATH = "/path/to/sessions"
```
--------------------------------
### Access Compressed Static Resource URL in Appier
Source: https://github.com/hivesolutions/appier/blob/master/doc/templates.md
Illustrates how to request a compressed version of a static resource in Appier by adding the `compress = True` argument to `url_for`. This can optimize bandwidth usage.
```HTML
```
--------------------------------
### Appier Accessing Uploaded Files
Source: https://github.com/hivesolutions/appier/blob/master/doc/requests.md
Demonstrates how to access uploaded files in Appier when handling 'multipart/form-data' POST requests. It shows how to retrieve a file object using `self.field()` and access its properties.
```Python
@appier.route("/file", "POST")
def hello(self):
file = self.field("form_file_name")
return "you uploaded a file of type %s named %s" % (file.mime, file.name)
```
--------------------------------
### Add Runtime Validations in Appier
Source: https://github.com/hivesolutions/appier/blob/master/doc/models.md
Illustrates how to add and execute custom validation methods at runtime for specific entities in Appier. This is useful for validations that are not applicable to all instances of a model.
```Python
@classmethod
def validate_password_strength(cls):
return [
appier.string_gt("_password", 5)
]
```
```Python
account.validate_extra("password_strength")
account.save()
```
--------------------------------
### Send Email with Plain Text Template (Python)
Source: https://github.com/hivesolutions/appier/blob/master/doc/email.md
Illustrates sending an email with a separate template for the plain text version. The `plain_template` argument is used to specify the file for the plain text content.
```Python
self.email(
"template.html.tpl",
plain_template = "plain_template.txt.tpl",
subject = "Test email",
sender = "Sender Name ",
receivers = ["receiver@hive.pt"]
)
```
--------------------------------
### Render Template with Data in Appier
Source: https://github.com/hivesolutions/appier/blob/master/doc/templates.md
Shows how to pass data from a controller to a Jinja2 template in Appier. The `models.Cat.find()` result is passed as the `cats` variable to 'cat/list.html.tpl'.
```Python
cats = models.Cat.find()
return self.template(
"cat/list.html.tpl",
cats = cats
)
```
--------------------------------
### Supervisor Configuration
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Sets the interval in seconds for peer checking and controls the timeout for peer health check operations.
```Python
SUPERVISOR_INTERVAL = 60.0
```
--------------------------------
### Generate Absolute URL for Handler in Appier
Source: https://github.com/hivesolutions/appier/blob/master/doc/templates.md
Demonstrates how to generate an absolute URL for a handler in Appier by setting `absolute = True` in the `url_for` method. This prefixes the URL with `BASE_URL` from configuration.
```HTML
List Cats
```
--------------------------------
### Configure Cache Settings
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Defines the cache manager and its storage path. Supports different cache backends like file, memory, or Redis. For file-based caching, a specific directory path is required.
```python
CACHE = "file"
CACHE_PATH = "/var/cache/appier"
```
--------------------------------
### Define Cat Model with Fields and Configuration
Source: https://github.com/hivesolutions/appier/blob/master/doc/models.md
This Python snippet demonstrates how to define a `Cat` model inheriting from `appier.Model`. It showcases the use of `appier.field` to declare attributes like `id` and `name`, specifying their types (`int`, `unicode`) and configurations such as `index` and `increment`.
```Python
class Cat(appier.Model):
id = appier.field(
type = int,
index = True,
increment = True
)
name = appier.field(
type = unicode,
index = True
)
```
--------------------------------
### Python - Cat Model URL Resolution
Source: https://github.com/hivesolutions/appier/blob/master/doc/models.md
Shows how to define a get_show_url method within the Cat model to resolve a route URL using the owner's url_for method.
```Python
class Cat(appier.Model):
id = appier.field(
type = int,
index = True,
increment = True
)
def get_show_url(self):
url = self.owner.url_for("cats.show", id = self.id)
return url
```
--------------------------------
### Appier SSL/TLS Configuration
Source: https://github.com/hivesolutions/appier/blob/master/doc/configuration.md
Configures SSL/TLS encryption for the Appier application. Requires paths to key and certificate files when SSL is enabled, and can force SSL for all requests.
```Python
SSL = False # Enable or disable SSL
KEY_FILE = None # Path to SSL key file (required if SSL is True)
CER_FILE = None # Path to SSL certificate file (required if SSL is True)
FORCE_SSL = False # Force all requests to use HTTPS
```
--------------------------------
### Configure Logging Level via Environment Variable
Source: https://github.com/hivesolutions/appier/blob/master/doc/logging.md
Sets the logging level for an application by exporting the LEVEL environment variable before running the script. Only messages at or above the specified level will be logged.
```Bash
LEVEL=ERROR python hello.py
```
--------------------------------
### Log Output with ERROR Level
Source: https://github.com/hivesolutions/appier/blob/master/doc/logging.md
Demonstrates the output when an application is run with the logging level set to ERROR. Only error and critical messages are displayed.
```Bash
error message
critical message
```
--------------------------------
### Loop Through Data in Jinja2 Template
Source: https://github.com/hivesolutions/appier/blob/master/doc/templates.md
Illustrates how to iterate over a list of objects (`cats`) within a Jinja2 template. Each `cat` object's `name` attribute is displayed in a table row.
```HTML
{% for cat in cats %}
| {{ cat.name }} |
{% endfor %}
```
--------------------------------
### Log Info Messages in Python
Source: https://github.com/hivesolutions/appier/blob/master/doc/logging.md
Logs an informational message using the logger object within an Appier application. This is a basic logging operation.
```Python
self.logger.info("information message")
```
--------------------------------
### Display Session Email in Template (HTML)
Source: https://github.com/hivesolutions/appier/blob/master/doc/sessions.md
Illustrates how to access and display a session variable, specifically 'email', within an HTML template using Appier's templating syntax.
```HTML
Logged in as {{ session.email }}
```
--------------------------------
### Log Warning Messages in Python
Source: https://github.com/hivesolutions/appier/blob/master/doc/logging.md
Logs a warning message using the logger object. This is useful for indicating potential issues that do not stop the application's execution.
```Python
self.logger.warn("warning message")
```