Skip to content

OmarSSpy/AlphaPY

Repository files navigation

ALPHA FRAMEWORK

Description:

The Alpha Framework is a minimalistic web framework designed to help beginners learn web development easily. With simplicity at its core, Alpha aims to provide a straightforward way to build web applications while offering essential features like routing, session management, and templating.

Ideal For Beginners:

Alpha was designed to help beginners. Whether you are a student learning how to build web apps or a hobbyist who wants to create simple projects, Alpha provides the essential tools needed without overwhelming complexity.

By using Alpha, you can quickly set up web applications, manage routing, handle sessions, and work with templates—all in a beginner-friendly environment. It’s perfect for small projects and educational purposes, providing a solid foundation for future usage of more complex frameworks.

Features

  • Routing system for handling HTTP requests
  • Built-in templating engine using Jinja2
  • Static file serving
  • Simple session management
  • Dynamic route handling
  • Database integration
  • Simple CLI to run your application
  • Built-in blueprint system for building modular applications
  • Security utils & JSON , URL related utils
  • Simple Middleware Integration

Getting Started

To install the Alpha Framework, you can either download the source code or install it via pip.

Installing From Source

  1. Clone the repository:
git clone https://github.com/OmarSSpy/alpha.git
  1. Navigate to the project directory:
cd alpha
  1. Install the framework:
python setup.py install

Installing via pip

  1. Make sure you have pip installed:
pip --version
  1. Simply run this command:
pip install alpha

Basic Usage

Alpha Imports

Here are what each import is used for:

from alpha import Alpha            
from alpha import Request          
from alpha import Database        
from alpha import Response         
from alpha import security_utils   
from alpha import utils            
from alpha import SessionManager   
from alpha import Blueprint        
from alpha import render_template  

Detailed Explanation

App Class (Alpha): This is the primary class that runs your web application. It’s responsible for setting up routes, handling requests, and sending responses.

Request: This class helps you handle incoming HTTP requests. It provides access to details like HTTP headers, request body, and other properties of the request.

Database (SQLite Integration): With the Database class, Alpha integrates SQLite3 databases. You can easily interact with databases—create tables, insert data, or fetch information.

Response: After processing a request, your application needs to send back a response. The Response class allows you to customize and send HTTP responses, including status codes, headers, and body content.

Security Utils: This module provides useful utilities for security, such as password hashing, input validation, and protection against common web vulnerabilities.

URL & JSON Utils: This utility class contains methods for handling URLs, query parameters, and generating JSON responses.

SessionManager: Alpha provides session management through cookies. This class helps you store and retrieve session data between user requests, making it easier to track users' states across different pages.

Blueprints: Blueprints help you organize your application into separate, reusable components. You can define routes and logic in isolated blueprints and then register them to the main application, making it easier to scale.

Render Template: This function allows you to render HTML templates with dynamic content. It integrates with the Jinja2 templating engine and enables the creation of dynamic web pages with variables.

Setting Up a Simple Application

Here’s a simple example of how to create a web application using the Alpha Framework:

from alpha import Alpha, Response, render_template

app = Alpha()

@app.route_path('/', methods=["GET"])
def home(params, session_data, request):
    return render_template('index', {title:"Welcome to Alpha!"})

if __name__ == "__main__":
    app.run()

Defining Routes

Alpha uses simple route decorators to define routes in your application:

@app.route_path('/', methods=["GET"])
def home(params, session_data, request):
    return Response(200, "This is the home page!")

@app.route_path('/about', methods=["GET"])
def about(params, session_data, request):
    return Response(200, "This is the about page!")

Using Templates

Alpha supports rendering HTML templates. Create a folder called templates/ and add an index.html file:

templates/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ title }}</h1>
</body>
</html>

Then, in your Python code, render this template with variables:

@app.route_path('/', methods=["GET"])
def home(params, session_data, request):
    return render_template('index', {title:"Welcome to Alpha!"})

Handling JSON Responses

You can easily return JSON responses using the jsonify() method:

from alpha import jsonify

app = Alpha()

@app.route_path('/api/data', methods=["GET"])
def data(params, session_data, request):
    return jsonify({"message": "Hello, World!"})

Redirects

You can perform redirects to another route:

@app.route_path('/redirect_example')
def redirect_example(params, session_data, request):
    return app.redirect('/about')

Running the Application

After defining your routes, run the application with:

if __name__ == "__main__":
    app.run()

Blueprints

You can also use blueprints to make your app modular:

blueprint.py:

from alpha import Blueprint, Response

bp = Blueprint("blueprint", __name__)

@bp.blueprint_route("/", methods=["GET"])
def index(params, session_data, request):
    if request.method == "GET":
        print("Test passed ")
        return Response(200, "Blueprint worked!")

app.py:

from blueprint import bp
from alpha import Alpha

app = Alpha()

app.register_blueprint(bp)

app.run()

Simple Session Management

You can manage simple session cookies using Alpha's SessionManager:

from alpha import SessionManager, Alpha, Response


# Initialize the session manager
session_manager = SessionManager()


@app.route_path('/set_session', methods=["GET"])
def set_session(params, session_data, request):
    session_data = {'user': 'Name'}
    response = Response(200, body="Session data set!")
    # Set the session
    return session_manager.set_session(response, session_data)

@app.route_path('/get_session', methods=["GET"])
def get_session(params, session_data, request):
    # Get the session data
    session_data = session_manager.get_session(request)
    if session_data:
        user = session_data.get('user', 'Guest')
        return Response(200, body=f"User: {user}")
    else:
        return Response(200, body="No session found!")

@app.route_path('/clear_session', methods=["GET"])
def clear_session(params, session_data, request):
    # Clear the session data
    response = Response(200, body="Session cleared!")
    session_manager.set_session(response, {})  
    return response

Database Integration

Alpha supports SQLite3 databases and has a class that helps you create your database and execute raw SQL queries into it:

from alpha import Database


db = Database("test.db")  


db.create_table("""
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        username TEXT NOT NULL,
        password TEXT NOT NULL
    )
""")


db.execute("INSERT INTO users (username, password) VALUES (?, ?)", ("alice", "password123"))


users = db.fetch_all("SELECT * FROM users")
print(users) 

user = db.fetch_one("SELECT * FROM users WHERE username=?", ("alice",))
print(user)  

Middleware Integration

Alpha supports basic middleware functions:

from alpha import Alpha, Response, Request

# Initialize Alpha app
app = Alpha()

# Define Middleware
def logger_middleware(request, response):
    """Logs each request"""
    print(f"[LOG] {request.method}")

def auth_middleware(request, response):
    """Checks if the request is authorized"""
    if "Authorization" not in request.headers:
        response.status_code = 401
        response.body = "Unauthorized"

# Register Middleware
app.use_middleware(logger_middleware)
app.use_middleware(auth_middleware)


# Define Routes
@app.route_path("/", ["GET"])
def home(params, session_data, request):
    return Response(200, "Welcome to Alpha!")

@app.route_path("/protected", ["GET"])
def protected(params, session_data, request):
    return Response(200, "This is a protected route!")


if __name__ == '__main__':
    app.run()

Conclusion

Alpha Framework is perfect for beginners who want to learn web development without getting overwhelmed by complex frameworks. With simple routing, templating, session management, and a clean, minimalistic design, you can quickly build applications while learning the basics of web development.

Contribution

If you would like to contribute to the Alpha framework, feel free to open an issue or create a pull request. Contributions are welcome to improve documentation, add features, or fix bugs.

License

Alpha is open-source and licensed under the Apache 2.0 License. See the LICENSE file for more details.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages