Skip to content

Basic Usage

ztrunk edited this page Apr 8, 2025 · 24 revisions

Basic Usage πŸ’‘

Configure your Project πŸ”§

After creating your project, you'll encounter a file named "project_name.py." Inside this file, you'll find multiple configuration sections. To run the application, simply execute this file.

Base Project structure:

project_name/
β”œβ”€β”€ baseapp/
β”‚   └── views/
β”‚       └── base.py        # LΓ³gica del controlador
β”œβ”€β”€ static/
β”‚   β”œβ”€β”€ base.css          # Estilos CSS
β”‚   └── base.js           # LΓ³gica JavaScript
β”œβ”€β”€ templates/
β”‚   β”œβ”€β”€ base.html         # Plantilla base para la estructura de la pΓ‘gina
β”‚   └── index.html        # Vista principal de la aplicaciΓ³n
β”œβ”€β”€ project_name.py       # Archivo principal de la aplicaciΓ³n PyPulse
└── window_logo.ico        # Icono de la ventana (opcional)

Example of setting file:

import os

from pypulse import Window, Aplication
from pypulse.Template import Template

# Specifying application Route
Aplication.Vars.APLICATION_PATH = os.path.dirname(os.path.abspath(__file__))

# Configuring applications
# If you create a new application, make sure to include it here.
APPLICATIONS = ["baseapp"]

# Application window settings
APP_SETTINGS = {
    'title': 'PyPulse App',
    'debug': False,
    'debug_file_name': 'debug.log',
    'window_size_x': 1270,
    'window_size_y': 720,
    'icon_path': os.path.join(
        Aplication.Vars.APLICATION_PATH, 'window_logo.ico')
}

# Defining the locations for templates and static files.
Template.TEMPLATE_PATH = os.path.join(
    Aplication.Vars.APLICATION_PATH, 'templates')
Template.STATIC_PATH = os.path.join(
    Aplication.Vars.APLICATION_PATH, 'static')

# setting apps
for x in APPLICATIONS:
    Aplication.SetAplication(x)

# Initializing window
browser = Window.LoadBrowser(**APP_SETTINGS)

Exploring How Applications Work in Your Project πŸ—οΈ

Applications in a PyPulse project work as modular components that help you organize and manage different parts of your web application.

  • Project Structure: When working with PyPulse applications, it's strongly advisable to embrace the Domain-Driven Design (DDD) architecture. When initiating a project, PyPulse provides a base application by default, which you have the flexibility to modify as needed. This base application primarily serves as a starting point for your "Hello World" application. The default structure it offers includes
baseapp
β”œβ”€β”€ domain
β”‚   └── user.py
└── views
    β”œβ”€β”€ home.py
    └── hacker.py
  • Registering an Application: To include an application in your project, open the project's settings file and add the following line. Make sure to place this line under the 'Setting Applications' section, typically found as # Setting Applications in the settings file.
Aplication.SetAplication('mymodule')

Exploring How Views Works πŸ”πŸ“š

In PyPulse, a view is a Python function view that takes a web request and returns a web response. Views are a fundamental part of PyPulse architecture and are responsible for handling the logic of your web application. They determine what data to display, what template to render, and how to respond to user interactions.

Here are some key points about views in PyPulse:

  1. Request Handling: Views receive HTTP requests from clients (usually web browsers) and process those requests. They contain the logic to handle various HTTP methods like GET, POST, PUT, DELETE, etc.
  2. Business Logic: Views encapsulate the business logic of your application. This can include database queries, calculations, form processing, and more.
  3. Templates: In many cases, views use templates to generate HTML responses. They pass data to the templates, which are responsible for rendering the final HTML that gets sent to the client.
  4. URL Routing: Views are connected to URLs through the URL dispatcher, that is set in the decorator.

Here's an example of a simple function-based view in PyPulse:

from pypulse.View import view
from pypulse.Template import RenderTemplate
from baseapp.domain import User

@view(name='home', path_trigger='/')
def home(request):
    user = User(type='Programmmer')

    if request.get('method') == 'POST':
        # your logic
        pass

    return RenderTemplate('home.html', {'user_type': user.type})

No matter where you place the view, as long as it's adorned with the @view(name='name', path_trigger='path') decorator, the view will be automatically registered within the application.

Example of GET request: {'method': 'GET', 'headers': {'Host': '127.0.0.1:63333', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) PyPulse/10.00 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9'}}

Example of POST request: {'method': 'POST', 'headers': {'Host': '127.0.0.1:63333', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) PyPulse/10.00 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9'}, 'body': {'name': 'test_body_name1', 'name2': 'test_body_name2'}}

  • Adding parameters to views, accepted types [str, float, int]
@view(name='test', path_trigger='/test/<str:parameter_1>/<float:parameter_2>/')
def test(request, parameter_1, parameter_2):
    return RenderTemplate('home.html')

Exploring How Templates Works πŸ“πŸ§

In PyPulse, templates are a fundamental part of the framework's architecture and are used to generate dynamic HTML content that is sent as a response to a user's request. Templates allow you to separate the presentation layer (HTML) from the business logic layer (Python code), promoting code reusability and maintainability. Here's an overview of how templates work in PyPulse:

  • To specify the location for your templates, navigate to your project's configuration and modify the TEMPLATE_PATH variable.
  • Template Files: PyPulse templates are typically stored in separate HTML files with a .html extension.
  • Template Language: PyPulse use Jinja2, which is a simplified and secure way to embed Python-like code within HTML templates. You can use template tags and filters to perform various operations within the templates. For example, you can use tags to loop through data, conditionally render content, or include other templates.
<!-- Example PyPulse template -->
<h1>{{ page_title }}</h1>
<ul>
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
</ul>
  • Context: Views in PyPulse pass a context dictionary to templates. This context contains data that can be accessed within the template. You can pass variables, objects, and query results to the template through the context.
from pypulse.View import view
from pypulse.Template import RenderTemplate

@view(name='my_view_name', path_trigger='my_path')
def my_view(request):
    items = ['Item 1', 'Item 2', 'Item 3']
    context = {
        'page_title': 'My Page',
        'items': items,
    }
    return RenderTemplate('my_template.html', context)
  • Rendering Templates: Views render templates using the render function, passing the request object, template file name, and context dictionary as parameters. The render function processes the template, substitutes the template tags with data from the context, and generates the final HTML response.
  • Template Inheritance: PyPulse templates support template inheritance, allowing you to create a base template with a common layout and structure and then extend or override specific sections in child templates. This promotes code reuse and consistency in your application's UI.
<!-- Base template (base.html) -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <div class="container">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
<!-- Child template (child.html) -->
{% extends "base.html" %}

{% block title %}Child Template{% endblock %}

{% block content %}
<p>This is content specific to the child template.</p>
{% endblock %}
  • Template Tags and Filters: PyPulse with Jinja2 provides a variety of built-in template tags and filters that you can use to perform common tasks within templates. Template tags allow you to control logic, while filters enable you to manipulate and format data.
  • Static Files: To specify the location for your static, navigate to your project's configuration and modify the STATIC_PATH variable.
  • Here's an example of how to reference a static file
<link rel="stylesheet" type="text/css" href="/base.css">
  • More info about the templating here Jinja2

Exploring How Redirection Works πŸ”„πŸ§

In PyPulse, redirection leads to another view. To achieve this redirection, you must pass the path_trigger to specify the destination view.

  • Example of redirection
@view(name='home', path_trigger='/')
def home(request):
    user = User(type='Programmmer')
    
    if request.get('method') == 'POST':
        return Redirect('/hacker')

    return RenderTemplate('home.html', {'user_type': user.type, 'path': '/'})

Next steps: