### Set Up Virtual Environment Manually Source: https://docs.masonite.dev/getting-started/installation Manually creates a virtual environment, activates it, and installs project dependencies from requirements.txt. Use this if you skipped virtual environment creation during project setup. ```bash cd blog python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install -r requirements.txt ``` -------------------------------- ### Run Test Project Source: https://docs.masonite.dev/digging-deeper/package-development Start the integrated test project to directly test your package's behavior. Your package is automatically installed and registered. ```bash python craft serve ``` -------------------------------- ### Install Project Dependencies Source: https://docs.masonite.dev/official-packages/collapsar/contributing Set up a virtual environment, activate it, and install all necessary Python packages listed in requirements.txt. ```bash python -m venv venv source venv/bin/activate python -m pip install -r requirements.txt ``` -------------------------------- ### Start Development Server Source: https://docs.masonite.dev/getting-started/create-a-blog Run this craft command to start the development server and make your application accessible locally. ```bash $ python craft serve ``` -------------------------------- ### Start Tinker with IPython Source: https://docs.masonite.dev/digging-deeper/tinker Use the -i flag to launch Tinker with IPython for an enhanced experience, including syntax highlighting and tab completion. Ensure IPython is installed (`pip install IPython`). ```bash python craft tinker -i ``` -------------------------------- ### Dependency Management Examples Source: https://docs.masonite.dev/prologue/release-cycle Examples of how to specify Masonite framework dependencies using different versioning constraints. ```text masonite-framework>=5,<6 ``` ```text masonite-framework~=5 ``` -------------------------------- ### Install NPM Dependencies Source: https://docs.masonite.dev/the-basics/compiling-assets Run this command to install all necessary dependencies for compiling assets. ```bash $ npm install ``` -------------------------------- ### Basic Model Queries Source: https://docs.masonite.dev/orm/models Once a model is defined, you can perform basic queries to fetch records. These examples show how to get the first record, all records, or records matching a specific condition. ```python user = User.first() users = User.all() active_users = User.where('active', 1).first() ``` -------------------------------- ### Install slackblocks Source: https://docs.masonite.dev/digging-deeper/notifications Install the slackblocks Python API to handle Block Kit formatting for Slack notifications. ```bash $ pip install slackblocks ``` -------------------------------- ### Example Output of 'env' Command Source: https://docs.masonite.dev/digging-deeper/scheduling An example of the output from the 'env' command, showing various environment variables including the PATH. ```text ... __CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0 PATH=/Library/Frameworks/Python.framework/Versions/3.11/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.11/bin PWD=/Users/Masonite/Programming/masonite ... ``` -------------------------------- ### Default Setup for the Whole Test Suite Source: https://docs.masonite.dev/testing/extending Use the `setUp()` method in your project's `TestCase` to apply state to every test, such as registering routes or setting default headers. Always call `super().setUp()` first. ```python from masonite.routes import Route from masonite.tests import TestCase as MasoniteTestCase class TestCase(MasoniteTestCase): def setUp(self): super().setUp() self.withHeaders({"X-Requested-With": "XMLHttpRequest"}) self.addRoutes( Route.get("/testing-only", "WelcomeController@show"), ) ``` -------------------------------- ### Example Database Configuration for Testing Source: https://docs.masonite.dev/testing/database-tests This example shows a typical database configuration file. It includes a 'testing' connection using SQLite, which is useful for isolated test environments. ```python # config/database.py DATABASES = { "default": "mysql", "mysql": { "host": "localhost", "driver": "mysql", "database": "app", "user": "root", "password": "", "port": 3306 } "testing": { "driver": "sqlite", "database": "test_database.sqlite3", }, } ``` -------------------------------- ### Basic Masonite Test Case Example Source: https://docs.masonite.dev/testing/getting-started An example of a simple unit test class that inherits from Masonite's TestCase. It demonstrates the basic structure including setUp and a simple assertion. ```python from masonite.tests import TestCase class SomeFeatureTest(TestCase): def setUp(self): super().setUp() def test_something(self): self.assertTrue(True) ``` -------------------------------- ### Create Environment File Source: https://docs.masonite.dev/official-packages/collapsar/contributing Copy the example environment file to create your local .env configuration file. ```bash cp .env-example .env ``` -------------------------------- ### Postgres Connection Options Example Source: https://docs.masonite.dev/orm/installation Example configuration for a Postgres connection in Masonite, demonstrating how to pass both direct psycopg2 arguments and server settings within the 'options' dictionary. ```json "postgres": { "host": "127.0.0.1", "driver": "postgres", "database": "masonite", "user": "root", "password": "", "port": 5432, "options": { "sslmode": "require", # psycopg2 connect argument "connect_timeout": 10, # psycopg2 connect argument "statement_timeout": 5000, # server setting, sent as -c statement_timeout=5000 } }, ``` -------------------------------- ### Example Policy for Post Model Source: https://docs.masonite.dev/security/authorization A concrete example of a PostPolicy demonstrating authorization logic for create and view actions. ```python from masonite.authorization import Policy class PostPolicy(Policy): def create(self, user): return user.email == "idmann509@gmail.com" def view(self, user, instance): return True def update(self, user, instance): return user.id == instance.user_id ``` -------------------------------- ### Publish Package Resources After Installation Source: https://docs.masonite.dev/digging-deeper/package-development After installing a package, you may need to publish its resources (like configuration or views) to your project using the `package:publish` command. ```bash $ python craft package:publish super-awesome-package ``` -------------------------------- ### Install Package via Pip Source: https://docs.masonite.dev/digging-deeper/package-development Install a released package from PyPi using pip, the standard Python package installer. ```bash $ pip install super-awesome-package ``` -------------------------------- ### Run Migrations and Serve Application Source: https://docs.masonite.dev/getting-started/create-a-blog After setting up the controller and view, run migrations and start the development server to see your changes. ```bash $ python craft migrate ``` ```bash $ python craft serve ``` -------------------------------- ### Install Masonite 5 Framework Source: https://docs.masonite.dev/upgrade-guide/masonite-4.0-to-5.0 Uninstall the legacy 'masonite' package and install the new 'masonite-framework' package with version constraints. ```bash $ pip uninstall masonite $ pip install "masonite-framework>=5,<6" ``` -------------------------------- ### Basic Table Creation SQL Source: https://docs.masonite.dev/orm/white-page This is an example of the SQL syntax used for creating a table. ```sql CREATE TABLE `table` ( `name` VARCHAR(255) ) ``` -------------------------------- ### Install and Run Waitress Source: https://docs.masonite.dev/getting-started/deployment Install Waitress and run your Masonite application using it as a WSGI server. A pure-Python alternative suitable for Windows. ```bash pip install waitress waitress-serve --port=8000 wsgi:application ``` -------------------------------- ### Install API Configuration Source: https://docs.masonite.dev/digging-deeper/api Run the `craft api:install` command to generate the `api.py` configuration file and set up JWT secrets. This command also generates a JWT_SECRET in your .env file. ```bash python craft api:install ``` -------------------------------- ### Install cookiecutter Source: https://docs.masonite.dev/digging-deeper/package-development Install the cookiecutter package globally or locally to use the template. ```bash $ pip install cookiecutter ``` -------------------------------- ### Qmark vs SQL Example Source: https://docs.masonite.dev/orm/white-page Illustrates the difference between direct SQL and Qmark query formats. Qmark format is recommended for security. ```sql SELECT * FROM `users` where `age` = '18' ``` ```sql SELECT * FROM `users` where `age` = '?' ``` -------------------------------- ### Enable CSRF Protection in setUp() Source: https://docs.masonite.dev/testing/http-tests Add `self.withCsrf()` to the `setUp()` method to enable CSRF protection for all tests in the class. ```python def setUp(self): super().setUp() self.withCsrf() ``` -------------------------------- ### Container Hook Examples Source: https://docs.masonite.dev/architecture/service-container Demonstrates setting up hooks for bind, make, and resolve events on a specific object type. ```python container.on_bind(Request, attribute_on_make) container.on_make(Request, attribute_on_make) container.on_resolve(Request, attribute_on_make) ``` -------------------------------- ### API Configuration File Example Source: https://docs.masonite.dev/digging-deeper/api This is an example of the generated `api.py` configuration file. It defines JWT settings, including the algorithm, secret, and the model to use for authentication. ```python """API Config""" from app.models.User import User from masonite.environment import env DRIVERS = { "jwt": { "algorithm": "HS512", "secret": env("JWT_SECRET"), "model": User, "expires": None, "authenticates": False, "version": None, } } ``` -------------------------------- ### Install Redis Package Source: https://docs.masonite.dev/digging-deeper/cache Command to install the necessary Python package for using the Redis cache driver. ```bash pip install redis ``` -------------------------------- ### Install Memcached Package Source: https://docs.masonite.dev/digging-deeper/cache Command to install the necessary Python package for using the Memcached cache driver. ```bash pip install pymemcache ``` -------------------------------- ### Initialize Project Environment Source: https://docs.masonite.dev/digging-deeper/package-development Run this command to install Masonite, development tools, and your package locally. It utilizes the Makefile provided in the default package layout. ```bash make init ``` -------------------------------- ### Install and Run Gunicorn Source: https://docs.masonite.dev/getting-started/deployment Install Gunicorn and run your Masonite application using it as a WSGI server. Recommended for Linux production environments. ```bash pip install gunicorn gunicorn --workers 4 --bind 0.0.0.0:8000 wsgi:application ``` -------------------------------- ### Install Vonage Python Client Source: https://docs.masonite.dev/digging-deeper/notifications Install the Vonage Python client (version 4 or above) to enable sending SMS notifications. ```bash $ pip install "vonage>=4" ``` -------------------------------- ### Install Masonite Framework Source: https://docs.masonite.dev/getting-started/installation Installs the Masonite framework package using pip. This command should be run after setting up your Python environment. ```bash $ pip install masonite-framework ``` -------------------------------- ### Method and Function Docstring Example Source: https://docs.masonite.dev/prologue/contributing-guide Methods and functions require docstrings that briefly describe their purpose and provide an example of usage. ```python def some_function(self): """This is a function that does x action. Then give an exmaple of when to use it """ ... code ... ``` -------------------------------- ### Run the Collapsar Application Source: https://docs.masonite.dev/official-packages/collapsar/contributing Start the development server to run the Collapsar application locally. ```bash python craft serve ``` -------------------------------- ### Build Project Assets Source: https://docs.masonite.dev/official-packages/collapsar/contributing Install Node.js dependencies and build the project's front-end assets using Vite. ```bash npm install npx vite build ``` -------------------------------- ### Model Query Example (Instance) Source: https://docs.masonite.dev/orm/white-page Performing a query using an instance of a model. This demonstrates the traditional object-oriented approach to querying. ```python result = User().where('...') ``` -------------------------------- ### Building a Seed for Testing Source: https://docs.masonite.dev/orm/seeding An example of a seed that creates a specific user record in the database. This is useful for setting up test data. ```python from masoniteorm.seeds import Seeder from models import User class UserTableSeeder(Seeder): def run(self): """Run the database seeds.""" User.create({ "username": "Joe", "email": "joe@masoniteproject.com", "password": "secret" }) ``` -------------------------------- ### Example Cron Job for Running Tasks Every Minute Source: https://docs.masonite.dev/digging-deeper/scheduling A cron job setup for UNIX-based systems to run the 'schedule:run' command every minute. Ensure the PATH is correctly set for your environment, especially if using a virtual environment. ```cron PATH=/Users/Masonite/Programming/project_name/venv/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.11/bin * * * * * cd /Users/Masonite/Programming/project_name && source venv/bin/activate && python craft schedule:run ``` -------------------------------- ### View Help for a Specific Command Source: https://docs.masonite.dev/digging-deeper/commands Prefix the command name with 'help' to view its documentation, including available arguments and options. This example shows help for the 'serve' command. ```bash python craft help serve ``` -------------------------------- ### Module Docstring Example Source: https://docs.masonite.dev/prologue/contributing-guide All module files should begin with a module docstring. Ensure there are no leading or trailing spaces around the descriptive sentence. ```python """This is a module to add support for Billing users.""" from masonite.request import Request ... ``` -------------------------------- ### get Source: https://docs.masonite.dev/orm/query-builder Executes the query and gets all records. ```APIDOC ## get ### Description Gets all records. Used in combination with other builder methods to finally execute the query. ### Method `get()` ``` -------------------------------- ### Start Queue Worker Source: https://docs.masonite.dev/getting-started/deployment Start a queue worker process to handle background jobs dispatched by your application. Requires a process manager like systemd or supervisor. ```bash python craft queue:work ``` -------------------------------- ### Compile Production Assets Source: https://docs.masonite.dev/getting-started/deployment Install frontend dependencies and compile production-ready assets if your application uses a frontend preset. ```bash npm install npm run prod ``` -------------------------------- ### Run Development Server with Custom Host and Port Source: https://docs.masonite.dev/digging-deeper/commands The 'serve' command starts the development server. You can specify the host and port it binds to using the --host and --port options. ```bash python craft serve --host 0.0.0.0 --port 9000 ``` -------------------------------- ### Install Collapsar Package Source: https://docs.masonite.dev/official-packages/collapsar/quickstart Install the Collapsar package using pip. ```bash pip install collapsar ``` -------------------------------- ### Using Built-in Request Facade Source: https://docs.masonite.dev/architecture/facades This example demonstrates accessing request input using the Request facade, imported from masonite.facades. ```python from masonite.facades import Request def show(self): avatar = Request.input('avatar_url') ``` -------------------------------- ### Model Query Example (Class) Source: https://docs.masonite.dev/orm/white-page Performing a query directly on the model class. This leverages Masonite's meta classing for a cleaner syntax. ```python result = User.where('...') ``` -------------------------------- ### Basic HTML Template Source: https://docs.masonite.dev/the-basics/views An example of a simple HTML template file located in the `templates` directory. ```html

Hello, {{ name }}

``` -------------------------------- ### Define a Route to a Controller Method Source: https://docs.masonite.dev/the-basics/controllers Maps a GET request to the root URL to the 'show' method of the 'WelcomeController'. ```python Route.get('/', 'WelcomeController@show') ``` -------------------------------- ### Create a Basic Controller with Craft Command Source: https://docs.masonite.dev/the-basics/controllers Generates a new controller file named 'WelcomeController' using the Masonite craft command. ```bash $ python craft controller Welcome ``` -------------------------------- ### Install Vue Plugin for Vite Source: https://docs.masonite.dev/the-basics/compiling-assets Install the Vue plugin as a development dependency and register it in your Vite configuration. ```bash $ npm install --save-dev vue @vitejs/plugin-vue ``` -------------------------------- ### Create a New Service Provider Source: https://docs.masonite.dev/architecture/service-providers Use the craft command to generate a new Service Provider file. This command creates a basic structure with 'register' and 'boot' methods. ```bash python craft provider DashboardProvider ``` -------------------------------- ### Create Virtual Environment Source: https://docs.masonite.dev/digging-deeper/package-development Use this command to create a new virtual environment for your project. Ensure you have Python 3 installed. ```bash python3 -m venv venv ``` -------------------------------- ### Install Pusher Python Package Source: https://docs.masonite.dev/digging-deeper/broadcasting Install the necessary Python package for Pusher integration using pip. ```bash pip install pusher ``` -------------------------------- ### Define a GET Route Source: https://docs.masonite.dev/the-basics/routing Create a GET route that maps a URL to a controller action. Ensure the controller is importable. ```python from masonite.routes import Route ROUTES = [ Route.get('/welcome', 'WelcomeController@show') ] ``` -------------------------------- ### Basic HTTP GET Request Source: https://docs.masonite.dev/testing/http-tests Performs a basic GET request to the root path and asserts that the response is OK. ```python def test_basic_request(self): self.get("/").assertOk() ``` -------------------------------- ### Get UNIX Timestamp Until Available Source: https://docs.masonite.dev/digging-deeper/rate-limiting Get the UNIX timestamp in seconds when the rate limit will be available again using `RateLimiter.available_at`. ```python RateLimiter.available_at(f"send_mail-{user.id}") #== 1646998321 ``` -------------------------------- ### Create a Basic Migration Source: https://docs.masonite.dev/orm/schema-and-migrations Run this command to create a new migration file in the databases/migrations directory. ```bash $ masonite-orm migration migration_for_users_table ``` -------------------------------- ### Publish Package to PyPI Source: https://docs.masonite.dev/digging-deeper/package-development Execute this command to build, upload your package to PyPI, and clean up build artifacts. Ensure your setup.py is up-to-date with the correct version number. ```bash make publish ``` -------------------------------- ### Masonite ORM Connection Resolver Setup Source: https://docs.masonite.dev/orm/orator-to-masonite-orm Masonite ORM's method for setting up the connection resolver with database details. ```python from masoniteorm.connections import ConnectionResolver DATABASES = { # ... } DB = ConnectionResolver().set_connection_details(DATABASES) ``` -------------------------------- ### Masonite ORM Database Configuration Source: https://docs.masonite.dev/orm/orator-to-masonite-orm Example of a Masonite ORM database configuration dictionary. This file should be located at 'config/database.py'. ```python import os DATABASES = { 'default': 'mysql', 'mysql': { 'driver': 'mysql', 'host': os.getenv('MYSQL_DATABASE_HOST'), 'user': os.getenv('MYSQL_DATABASE_USER'), 'password': os.getenv('MYSQL_DATABASE_PASSWORD'), 'database': os.getenv('MYSQL_DATABASE_DATABASE'), 'port': os.getenv('MYSQL_DATABASE_PORT'), 'prefix': '', 'options': { 'charset': 'utf8mb4', }, 'log_queries': True }, 'postgres': { 'driver': 'postgres', 'host': os.getenv('POSTGRES_DATABASE_HOST'), 'user': os.getenv('POSTGRES_DATABASE_USER'), 'password': os.getenv('POSTGRES_DATABASE_PASSWORD'), 'database': os.getenv('POSTGRES_DATABASE_DATABASE'), 'port': os.getenv('POSTGRES_DATABASE_PORT'), 'prefix': '', 'log_queries': True }, 'sqlite': { 'driver': 'sqlite', 'database': 'orm.sqlite3', 'prefix': '', 'log_queries': True }, 'mssql': { 'driver': 'mssql', 'host': os.getenv('MSSQL_DATABASE_HOST'), 'user': os.getenv('MSSQL_DATABASE_USER'), 'password': os.getenv('MSSQL_DATABASE_PASSWORD'), 'database': os.getenv('MSSQL_DATABASE_DATABASE'), 'port': os.getenv('MSSQL_DATABASE_PORT'), 'prefix': '', 'log_queries': True }, } ``` -------------------------------- ### Publish All Package Resources Source: https://docs.masonite.dev/digging-deeper/package-development Use the `package:publish` command to publish all resources for a specified package. Replace 'super_awesome' with your package's name. ```bash $ python craft package:publish super_awesome ``` -------------------------------- ### Example Mail Configuration File Source: https://docs.masonite.dev/getting-started/configuration This file defines email-related configuration options, including the default sender email and driver settings. It utilizes environment variables for dynamic values. ```python from masonite.environment import env FROM_EMAIL = env("MAIL_FROM", "no-reply@masonite.com") DRIVERS = { "default": env("MAIL_DRIVER", "terminal"), "smtp": { "host": env("MAIL_HOST"), "port": env("MAIL_PORT", "587"), "username": env("MAIL_USERNAME"), "password": env("MAIL_PASSWORD"), "from": FROM_EMAIL, } } ``` -------------------------------- ### Install Masonite Debugbar Package Source: https://docs.masonite.dev/official-packages/masonite-debugbar Install the Masonite Debugbar package using pip. Note that the import name is 'debugbar'. ```bash $ pip install masonite-framework-debugbar ``` -------------------------------- ### Registering Routes for Testing Source: https://docs.masonite.dev/testing/http-tests Shows how to register routes specifically for testing purposes using the addRoutes() method within setUpClass. ```python @classmethod def setUpClass(cls): super().setUpClass() cls.addRoutes( Route.get("/", "TestController@show"), Route.post("/", "TestController@show"), ) ``` -------------------------------- ### Specify Selects with Get Method Source: https://docs.masonite.dev/orm/models Columns to select can be specified directly within the get() method, alongside other query constraints. ```python store.where("active", 1).get(["username", "administrator as is_admin"]) #== SELECT `username`, `administrator` as is_admin FROM `users` WHERE `active` = 1 ``` -------------------------------- ### Using a Custom Facade Source: https://docs.masonite.dev/architecture/facades After defining a custom facade, this shows how to import and use it in your application. ```python from app.facades import YourFacade YourFacade.method() ``` -------------------------------- ### Start Masonite Tinker Source: https://docs.masonite.dev/digging-deeper/tinker Run this command to enter the Tinker environment. It provides a Python shell with the application container, models, and helpers imported. ```bash python craft tinker ``` -------------------------------- ### Build Welcome Email Listener Source: https://docs.masonite.dev/digging-deeper/events Example of a listener that sends an email when an event is fired. It imports the `WelcomeMailable` class and uses the `mail` container to send the email. ```python from app.mailables.WelcomeMailable import WelcomeMailable class WelcomeEmail: def handle(self, event): from wsgi import application application.make("mail").send( WelcomeMailable().to('idmann509@gmail.com') ) ``` -------------------------------- ### Create Application with Flags (API, Postgres) Source: https://docs.masonite.dev/getting-started/installation Creates a new Masonite application named 'blog' with specific configurations: API-ready, PostgreSQL database, and no interactive prompts. Useful for scripting. ```bash $ masonite new blog --api --db=postgres --no-input ``` -------------------------------- ### Run Database Migrations Source: https://docs.masonite.dev/official-packages/collapsar/contributing Apply database migrations using the 'craft migrate' command to set up your local database schema. ```bash python craft migrate ``` -------------------------------- ### Start Queue Worker Source: https://docs.masonite.dev/digging-deeper/queues Run the queue:work command to start a terminal process that listens for and processes jobs from the queue. ```bash $ python craft queue:work ``` -------------------------------- ### Add Blog Routes to Masonite Source: https://docs.masonite.dev/getting-started/create-a-blog Adds a new GET route for '/blog' that points to the 'show' method of 'BlogController'. This assumes the BlogController already exists. ```python ROUTES = [ Route.get('/', 'WelcomeController@show').name('welcome'), # Blog Routes Route.get('/blog', 'BlogController@show') ] ``` -------------------------------- ### Build a Basic Query with QueryBuilder Source: https://docs.masonite.dev/orm/white-page Initiates a query on the User model and returns a QueryBuilder instance. This is the starting point for chaining further query modifications. ```python user = User.where('age', 18) #== ``` -------------------------------- ### Scaffold Authentication Files Source: https://docs.masonite.dev/security/authentication Run this command to generate controllers, views, and mailables for a basic authentication system. ```bash craft auth ``` -------------------------------- ### Install Python Dev Packages (Debian/Ubuntu) Source: https://docs.masonite.dev/getting-started/installation Installs necessary Python development packages and libraries for Debian/Ubuntu based Linux distributions. ```bash $ sudo apt install python3-dev python3-pip libssl-dev build-essential python3-venv ``` -------------------------------- ### Adding a Custom Helper Method Source: https://docs.masonite.dev/testing/extending Define custom methods on your `TestCase` to encapsulate common setup logic, such as logging in a specific user. ```python from masonite.tests import TestCase as MasoniteTestCase from app.models.User import User class TestCase(MasoniteTestCase): def actingAsAdmin(self): admin = User.where("is_admin", 1).first() return self.actingAs(admin) ``` -------------------------------- ### Install Python Dev Packages (Specific Version) Source: https://docs.masonite.dev/getting-started/installation Installs specific Python development packages, like python3.10-dev, for Debian/Ubuntu based Linux distributions. ```bash $ sudo apt-get install python3.10-dev python3-pip libssl-dev build-essential python3-venv ``` -------------------------------- ### Compile Assets for Production Source: https://docs.masonite.dev/the-basics/compiling-assets Run this command to compile your frontend assets for production deployment. ```bash $ npm run production ``` -------------------------------- ### Get Error Messages for a Specific Field Source: https://docs.masonite.dev/the-basics/validation Retrieve a list of all error messages associated with a given field key from the MessageBag using the `get()` method. ```python errors.get('email') """ ['Your email is required'] """ ``` -------------------------------- ### Basic Service Provider Structure Source: https://docs.masonite.dev/architecture/service-providers A simple Service Provider demonstrating how to bind a class into the Service Container during registration and access it in the boot method. Ensure the 'User' class is defined elsewhere. ```python from masonite.providers import Provider class YourProvider(Provider): def __init__(self, application): self.application = application def register(self): self.application.bind('User', User) def boot(self): print(self.application.make('User')) ``` -------------------------------- ### Get the Last Element of a Collection Source: https://docs.masonite.dev/orm/collections Retrieves the last element from a collection. An optional truth test can be provided to get the last element that satisfies a condition. ```python collection = Collection([1, 2, 3, 4]) last = collection.last(lambda item: item < 3) #== 2 ``` -------------------------------- ### Accessing Configuration Values with Config Facade Source: https://docs.masonite.dev/getting-started/configuration Demonstrates how to retrieve configuration values using the `Config` facade. A default value can be provided if the configuration key does not exist. ```python from masonite.facades import Config Config.get("mail.from_email") # a default value can be provided Config.get("database.mysql.port", 3306) ``` -------------------------------- ### Define a GET Request Route Source: https://docs.masonite.dev/getting-started/create-a-blog Defines a simple GET route in Masonite that maps a URI to a controller method. Ensure the Route class is imported. ```python from masonite.routes import Route ROUTES = [ Route.get('/url', 'Controller@method') ] ``` -------------------------------- ### Install Masonite in Editable Mode Source: https://docs.masonite.dev/prologue/contributing-guide Installs the Masonite package in editable mode, allowing immediate reflection of code changes in your project. This is useful for developing the framework itself. ```bash git clone http://github.com/your-username/masonite.git pip install -e . ``` -------------------------------- ### Create and Query a Model Source: https://docs.masonite.dev/orm/introduction Demonstrates creating a new model instance and performing a query to retrieve recent posts. This snippet requires the `Model` class to be imported from `masoniteorm.models`. ```python from masoniteorm.models import Model class Post(Model): __fillable__ = ["title", "body"] post = Post.create({"title": "Hello World", "body": "My first post"}) recent = Post.where("created_at", ">", "2026-01-01").order_by("created_at", "desc").get() ``` -------------------------------- ### Install Masonite ORM via Pip Source: https://docs.masonite.dev/orm/installation Install the Masonite ORM package using pip. Ensure you specify a version range compatible with Masonite framework ORM. ```bash $ pip install "masonite-framework-orm>=3,<4" ``` -------------------------------- ### Install Python Dev Packages (Enterprise Linux) Source: https://docs.masonite.dev/getting-started/installation Installs Python development and OpenSSL development packages for Enterprise Linux distributions like Fedora, CentOS, and RHEL. ```bash # dnf install python-devel openssl-devel ``` -------------------------------- ### Registering Package Configuration Source: https://docs.masonite.dev/digging-deeper/package-development Demonstrates how to register a package's configuration file using the `config()` method within the `configure` method of a `PackageProvider`. Set `publish=True` to allow users to publish this configuration to their project. ```python def configure(self): ( self.root("super_awesome_package") .name("super_awesome") .config("config/super_awesome.py", publish=True) ) ``` -------------------------------- ### Mail Facade Type Hinting Source: https://docs.masonite.dev/architecture/facades This example illustrates how to add type hinting for a custom facade, specifically the Mail facade, using a .pyi file for better editor support. Note that method bodies are replaced with '...'. ```python from typing import TYPE_CHECKING if TYPE_CHECKING: from ..mail import Mailable class Mail: """Handle sending e-mails from Masonite via different drivers.""" def mailable(mailable: "Mailable") -> "Mail": ... def send(driver: str = None): ... ``` -------------------------------- ### all Source: https://docs.masonite.dev/orm/query-builder Gets all records from the query. ```APIDOC ## all ### Description Gets all records. ### Method `all()` ``` -------------------------------- ### Import and Initialize QueryBuilder Source: https://docs.masonite.dev/orm/query-builder Import the QueryBuilder class and initialize it by specifying the table to query. ```python from masoniteorm.query import QueryBuilder builder = QueryBuilder().table("users") ``` -------------------------------- ### last Source: https://docs.masonite.dev/orm/query-builder Gets the last record from the query. ```APIDOC ## last ### Description Gets the last record. ### Method `last()` ``` -------------------------------- ### first Source: https://docs.masonite.dev/orm/query-builder Gets the first record from the query. ```APIDOC ## first ### Description Gets the first record. ### Method `first()` ``` -------------------------------- ### Get Host Source: https://docs.masonite.dev/the-basics/request Retrieve the current host from the request. This excludes the subdomain. ```python from masonite.request import Request #.. def show(self, request: Request): # URI: work.example.com request.get_host() #== example.com ``` -------------------------------- ### Scaffold Authentication System Source: https://docs.masonite.dev/getting-started/create-a-blog Run this craft command to generate controllers, routes, and views for user registration and authentication. ```bash $ python craft auth ``` -------------------------------- ### MySQL LIMIT Clause Source: https://docs.masonite.dev/orm/white-page Example of the MySQL syntax for limiting query results. ```sql SELECT * from `users` LIMIT 1 ``` -------------------------------- ### Get the First Record Source: https://docs.masonite.dev/orm/query-builder Fetch only the first record from the table using the first() method. ```python builder.table('users').first() # SELECT * from `users` LIMIT 1 ``` -------------------------------- ### Run Masonite Migrations and Development Server Source: https://docs.masonite.dev/getting-started/installation Executes database migrations and starts the Masonite development server. Ensure your virtual environment is activated before running these commands. ```bash python craft migrate python craft serve ``` -------------------------------- ### Get Cookie Value Source: https://docs.masonite.dev/the-basics/views Retrieve the value of a specific cookie using the cookie() helper. ```html

Token: {{ cookie('token') }}

``` -------------------------------- ### Registering Package Routes and Controllers Source: https://docs.masonite.dev/digging-deeper/package-development Illustrates how to register route files and specify controller locations for a package. The `controllers()` method should be called before `routes()` to ensure controllers are resolved correctly. ```python def configure(self): ( self.root("super_awesome_package") .name("super_awesome") .controllers("controllers") # before routes ! .routes("routes/api.py", "routes/web.py") ) ``` -------------------------------- ### Create a Blog View Template Source: https://docs.masonite.dev/getting-started/create-a-blog Create an HTML file in the 'templates' directory to serve as the view for your blog route. ```html This is a blog ``` -------------------------------- ### Configure PyPI Authentication Source: https://docs.masonite.dev/digging-deeper/package-development Example of a .pypirc file configuration using an API token for authentication with PyPI. Replace 'pypi-AgEIcHlwaS5vcmcCJGNjYjA4M...' with your actual token. ```ini [distutils] index-servers = pypi pypitest [pypi] username=__token__ password=pypi-AgEIcHlwaS5vcmcCJGNjYjA4M... ``` -------------------------------- ### Creating a Custom Facade Source: https://docs.masonite.dev/architecture/facades This shows the basic structure for creating your own facade by inheriting from the base Facade class and defining a container key. ```python from masonite.facades import Facade class YourFacade(metaclass=Facade): key = 'container_key' ``` -------------------------------- ### Aggregate Column Count Source: https://docs.masonite.dev/orm/query-builder Get the count of a column. An alias can be specified using the 'as' modifier. ```python .count('column as alias') ``` -------------------------------- ### Aggregate Column Sum Source: https://docs.masonite.dev/orm/query-builder Get the sum of a column. An alias can be specified using the 'as' modifier. ```python .sum('column as alias') ``` -------------------------------- ### Using Built-in Mail Facade Source: https://docs.masonite.dev/architecture/facades This shows how to use the Mail facade as a shortcut to send emails, importing it from the masonite.facades namespace. ```python from masonite.facades import Mail Mail.send() ``` -------------------------------- ### Aggregate Column Average Source: https://docs.masonite.dev/orm/query-builder Get the average of a column. An alias can be specified using the 'as' modifier. ```python .avg('column as alias') ``` -------------------------------- ### Initialize Pusher Client Instance Source: https://docs.masonite.dev/digging-deeper/broadcasting Create a new Pusher instance on the client-side using your application's key and cluster. It is recommended to use environment variables for credentials instead of hardcoding them. ```javascript const pusher = new Pusher("478b45309560f3456211", { cluster: "eu", }); ``` -------------------------------- ### Get All Records Source: https://docs.masonite.dev/orm/query-builder Fetch all records from a table using the all() method. This is typically used when no chaining is involved. ```python builder.table('users').all() # SELECT * from `users` ``` -------------------------------- ### Checking Route Existence Source: https://docs.masonite.dev/testing/http-tests Verifies if a route exists by using the get and post test methods. ```python def test_route_exists(self): self.assertTrue(self.get('/testing')) self.assertTrue(self.post('/testing')) ``` -------------------------------- ### Show All Posts Method Source: https://docs.masonite.dev/getting-started/create-a-blog Retrieves all posts from the database and renders the 'posts' view, passing the list of posts to the template. ```python from app.models.Post import Post ... def show(self, view: View): posts = Post.all() return view.render('posts', {'posts': posts}) ``` -------------------------------- ### Get Request Method Source: https://docs.masonite.dev/the-basics/request Retrieve the current request method. Ensure the Request class is imported. ```python from masonite.request import Request #.. def show(self, request: Request): request.get_request_method() #== PUT ``` -------------------------------- ### Create a Full Path URL Source: https://docs.masonite.dev/digging-deeper/helpers Use the url helper to create a full URL based on the APP_URL configuration. It accepts a path and optional query parameters. ```python from masonite.helpers import url url.url("/dashboard") #== example.com/dashboard ``` ```python url.url("/search/users", query_params={"search": "John Doe" "order": "asc"}) #== http://masonite.app/users/?search=John%2Doe&order=asc ``` -------------------------------- ### Create Migration with Table Creation Boilerplate Source: https://docs.masonite.dev/orm/schema-and-migrations Use the --create flag to generate a migration file with boilerplate code for creating a new table. ```bash $ masonite-orm migration migration_for_users_table --create users ``` -------------------------------- ### Get Request Path Source: https://docs.masonite.dev/the-basics/request Retrieve the current request URI. Ensure the Request class is imported. ```python from masonite.request import Request #.. def show(self, request: Request): request.get_path() #== /dashboard/1 ``` -------------------------------- ### Route for Showing All Posts Source: https://docs.masonite.dev/getting-started/create-a-blog Defines a GET route for '/posts' that maps to the 'show' method in the PostController. ```python Route.get('/posts', 'PostController@show') ``` -------------------------------- ### Create PyPI Configuration File Source: https://docs.masonite.dev/digging-deeper/package-development Generate the .pypirc file in your home directory to configure PyPI credentials. This command moves the file to the correct location. ```bash make pypirc ``` -------------------------------- ### Create New Masonite Application Source: https://docs.masonite.dev/getting-started/installation Creates a new Masonite application named 'blog'. This command initiates an interactive wizard to configure the application stack, frontend preset, and database. ```bash $ masonite new blog ``` -------------------------------- ### Aggregate Column Min Source: https://docs.masonite.dev/orm/query-builder Get the minimum value of a column. An alias can be specified using the 'as' modifier. ```python .min('column as alias') ``` -------------------------------- ### Registering Package Migrations Source: https://docs.masonite.dev/digging-deeper/package-development Shows how to register migration files from a package using the `migrations()` method. These files will be published to the project's database migrations directory when the package publish command is run. ```python def configure(self): ( self.root("super_awesome_package") .name("super_awesome") .migrations("migrations/create_some_table.py", "migrations/create_other_table.py") ) ``` -------------------------------- ### Aggregate Column Max Source: https://docs.masonite.dev/orm/query-builder Get the maximum value of a column. An alias can be specified using the 'as' modifier. ```python .max('column as alias') ``` -------------------------------- ### Execute Query with Chained Methods Source: https://docs.masonite.dev/orm/query-builder Use the get() method to execute a query after chaining multiple methods. ```python builder.table('users').select('username').get() ``` -------------------------------- ### Add Masonite Classifier to setup.py Source: https://docs.masonite.dev/digging-deeper/package-development Include the 'Framework :: Masonite' classifier in your setup.py file to make your package discoverable on PyPI as a Masonite package. ```python # setup.py classifiers=[ #... "Framework :: Masonite", ] ``` -------------------------------- ### Create Resource with Craft Source: https://docs.masonite.dev/official-packages/collapsar/quickstart Generate a new resource for a Masonite Model using the craft command. ```bash python craft resource MyModel ``` -------------------------------- ### Get Subdomain from Host Source: https://docs.masonite.dev/the-basics/request Extract the subdomain from the incoming request host. Assumes a valid host format. ```python from masonite.request import Request #.. def show(self, request: Request): # URI: work.example.com request.get_subdomain() #== work ``` -------------------------------- ### Show Migration SQL Dumps Source: https://docs.masonite.dev/orm/schema-and-migrations Preview the SQL statements that will be executed by migrations without actually running them. Use the `-s` or `--show` flag with `craft migrate` or `craft migrate:rollback`. ```bash python craft migrate -s ``` -------------------------------- ### Get Header from Request Source: https://docs.masonite.dev/the-basics/request Retrieve a specific header from the incoming request. The Request class must be imported. ```python from masonite.request import Request #.. def show(self, request: Request): request.header('X-Custom') ``` -------------------------------- ### Get Cookie from Request Source: https://docs.masonite.dev/the-basics/request Fetch a cookie from the incoming request headers. Ensure the Request class is imported. ```python from masonite.request import Request #.. def show(self, request: Request): request.cookie('Accepted-Cookies') ``` -------------------------------- ### Specify Connection with QueryBuilder Source: https://docs.masonite.dev/orm/query-builder Initialize the QueryBuilder and specify a connection on the fly using the 'on' method. ```python from masoniteorm.query import QueryBuilder builder = QueryBuilder().on('staging').table("users") ``` -------------------------------- ### Render a View from Controller Source: https://docs.masonite.dev/the-basics/controllers Renders a specific view file ('views.welcome') using the injected View class. ```python def show(self, view: View): return view.render("views.welcome") ``` -------------------------------- ### Get Authenticated User Source: https://docs.masonite.dev/security/authentication Retrieve the currently authenticated user object. Returns None if no user is authenticated. ```python from masonite.authentication import Auth from masonite.request import Request def login(self, auth: Auth, request: Request): user = auth.user() #== ``` -------------------------------- ### Create a New Test File with Craft Source: https://docs.masonite.dev/testing/getting-started Use the Craft CLI to quickly generate a new test file and class structure. This command creates a basic test file in the correct directory. ```bash python craft test SomeFeatureTest ``` -------------------------------- ### Access Shared Variable in Template Source: https://docs.masonite.dev/the-basics/views Example of how a globally shared variable can be accessed within an HTML template. ```html
Copyright {{ copyright }}
``` -------------------------------- ### Implement Post Creation in Store Method Source: https://docs.masonite.dev/getting-started/create-a-blog This snippet shows the implementation of the `store` method in `BlogController.py`. It imports the `Post` model and `Request` object to create a new post using form input and associates it with the authenticated user. ```python from app.models.Post import Post from masonite.request import Request # ... def store(self, request: Request): Post.create( title=request.input('title'), body=request.input('body'), author_id=request.user().id ) return 'post created' ``` -------------------------------- ### Method Docstring with Dependencies Example Source: https://docs.masonite.dev/prologue/contributing-guide When methods have dependencies or parameters, specify them in the docstring, including their type and a brief description. For object dependencies, provide the module path. ```python def route(self, route, output): """Load the route into the class. This also looks for the controller and attaches it to the route. Arguments: route {string} -- This is a URI to attach to the route (/dashboard/user). output {string|object} -- Controller to attach to the route. Returns: self """ ``` ```python def __init__(self, request: Request, csrf: Csrf, view: View): """Initialize the CSRF Middleware Arguments: request {masonite.request.Request} -- The normal Masonite request class. csrf {masonite.auth.Csrf} -- CSRF auth class. view {masonite.view.View} -- The normal Masonite view class. Returns: self """ pass ``` -------------------------------- ### Serve Static Files from S3 Configuration Source: https://docs.masonite.dev/the-basics/static-files Example of configuring S3 as a static file storage with a specific bucket path. This configuration is used with the `asset()` template function. ```python .... 's3': { 's3_client': 'sIS8shn...' ... 'path': 'https://s3.us-east-2.amazonaws.com/bucket' }, .... ``` -------------------------------- ### Get Route Parameter Source: https://docs.masonite.dev/the-basics/request Access route parameters from the request object. Ensure the parameter is defined in your route definition. ```python from masonite.request import Request #.. def show(self, request: Request): # GET /dashboard?user_id=1 request.param('user_id') #== 1 ``` -------------------------------- ### Displaying Files with Asset Helper Source: https://docs.masonite.dev/digging-deeper/filesystem Combines a base path from filesystem configuration with a filename to generate a displayable URL for assets. Requires the `path` to be set in the disk configuration. ```html ```