Skip to main content

Python web framework building for APIs

Project description

#PyLord: Python Web Framework built for creating APIs

purpose

PyPI - Version

PyLord is a Python web framework built for building APIs

It's a WSGI framework and can be used with any WSGI application server such as Gunicorn/Waitress

pip install pylord

How to use it

Basic Usage

import threading

from pylord.app import PyLordApp
from pylord.orm import ForeignKey, Table, Column, Database

threading_local = threading.local()
app = PyLordApp()


# you can add allowed methods in you function_handler
@app.route("/home", allowed_methods=["get"])
def home(request, response):
    response.text = "hi this is home page"


@app.route("/about")
def about(request, response):
    response.text = 'hi this is about page'


@app.route("/hello/{name}")
def generating(request, response, name):
    response.text = f"hello {name}"


# working with class
@app.route("/book")
class Books:
    def get(self, request, response):
        response.text = "this is get method"

    def post(self, request, response):
        response.text = "endpoint to create a book"


# route your class here
def new_handler(req, resp):
    resp.text = "New Handler"


app.add_route("/new_handler", new_handler)


# for creating any exception
def on_exception(req, resp, exc):
    resp.text = str(exc)


app.add_exception_handler(on_exception)


@app.route("/exception")
def exception_throwing_handler(req, resp):
    raise AttributeError("some exception")


# working with json
@app.route("/json")
def json_handler(req, resp):
    response_data = {"name": "asasa"}
    resp.json = response_data


def get_db():
    if not hasattr(threading_local, "db"):
        threading_local.db = Database("./test_main.db")
    return threading_local.db


class User(Table):
    username = Column(str)
    email = Column(str)
    password_hash = Column(str)


class Product(Table):
    user = ForeignKey(User)
    name = Column(str)
    price = Column(int)


from werkzeug.security import generate_password_hash, check_password_hash


def hash_password(password):
    return generate_password_hash(password)


def check_password(password, hashed_password):
    return check_password_hash(hashed_password, password)


@app.route("/user_register", allowed_methods=['post'])
def user_register(req, resp):
    db = get_db()

    data = req.json
    username = data.get("username")
    email = data.get("email")
    password1 = data.get("password1")
    password2 = data.get("password2")

    if not all([username, email, password1, password2]):
        resp.status_code = 400
        resp.json = {"error": "Barcha qatorlarni to'ldiring"}
        return

    if password1 != password2:
        resp.status_code = 400
        resp.json = {"error": "Parollar mos kelmayapti"}
        return

    existing_user_id = db.get_user(User, field_name="username", value=username)
    existing_user_email = db.get_user(User, field_name="email", value=email)
    if existing_user_id:
        resp.status_code = 400
        resp.json = {"error": "User already exists"}
        return
    elif existing_user_email:
        resp.status_code = 400
        resp.json = {"error": "Email already exists"}
        return

    hashed_password = hash_password(password1)

    new_user = User(username=username, email=email, password_hash=hashed_password)
    db.save(new_user)

    resp.status_code = 201
    resp.json = {
        "message": "User registered successfully",
        "user_id": new_user.id,
        "username": username,
        "email": email
    }

``` python 

import jwt
import datetime
import secrets
from functools import wraps

# just for test
SECRET_KEY = "your_secret_key"


def generate_token(user_id, username):
    payload = {
        "user_id": user_id,
        "username": username,
        "exp": datetime.datetime.utcnow() + datetime.timedelta(days=3)
    }
    return jwt.encode(payload, SECRET_KEY, algorithm="HS256")


def auth_required(f):
    @wraps(f)
    def decorated(req, resp, *args, **kwargs):
        auth_header = req.headers.get("Authorization")

        def reject(msg):
            resp.status_code = 401
            resp.json = {"error": msg}
            return

        if not auth_header or not auth_header.startswith("Bearer "):
            return reject("Token Required!")

        try:
            token = auth_header.split("Bearer ")[1]
            payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
            req.user_id = payload.get("user_id")
            req.username = payload.get("username")
        except (IndexError, AttributeError):
            return reject("Incorrect Token!")
        except jwt.ExpiredSignatureError:
            return reject("Token Expired!")
        except jwt.InvalidTokenError:
            return reject("Invalid Token")

        return f(req, resp, *args, **kwargs)

    return decorated
@app.route("/login", allowed_methods=['post'])
def login(req, resp):
    db = get_db()

    data = req.json
    username = data.get("username")
    password = data.get("password1")

    if not username or not password:
        resp.status_code = 400
        resp.json = {"message": "Username va password kiritish shart!"}

    # user = db.conn.execute("SELECT id, password_hash FROM user WHERE username = ?", (username,)).fetchone()
    user = db.get_user(User, field_name="username", value=username)

    if not user or not check_password(password, user["password_hash"]):
        resp.status_code = 401
        resp.json = {"error": "Noto‘g‘ri username yoki parol!"}

    token = generate_token(user["id"], username=username)

    resp.status_code = 200
    resp.json = {"token": token}
    

@app.route("/create_product", allowed_methods=['post'])
def create_product(req, resp):
    db = get_db()
    db.create(Product)
    data = req.json

    try:

        user = db.get(User, data['user'])
        if not user:
            resp.status_code = 404
            resp.json = {"error": "User not found"}
            return

        product = Product(
            user=user,
            name=data["name"],
            price=data['price']
        )

        db.save(product)

        resp.status_code = 201
        resp.json = {"id": product.id, "user": user.username, "name": product.name, "price": product.price}

    except Exception as e:
        resp.status_code = 500
        resp.json = {"error": str(e)}


@app.route("/get_product/{id:d}", allowed_methods=['get'])
def get_product(req, resp, id):
    db = get_db()

    product = db.get(Product, id=id)

    if not product:
        resp.status_code = 404
        resp.json = {"error": "Product not found"}
        return

    resp.status_code = 200
    resp.json = {"user": product.user.username, "name": product.name, "price": product.price}

Unit Tests

The recommended way of writing unit tests is with pytest. There are two built in fixtures that you may want to use when writing unit tests with PyLord. The first one is app which is an instance of the main API class:

def test_route_overlap_throws_exception(app):
    @app.route("/")
    def home(req, resp):
        resp.text = "Welcome Home."

    with pytest.raises(AssertionError):
        @app.route("/")
        def home2(req, resp):
            resp.text = "Welcome Home2."

The other one is client that you can use to send HTTP requests to your handlers. It is based on the famous requests and it should feel very familiar:

def test_parameterized_route(app, client):
    @app.route("/{name}")
    def hello(req, resp, name):
        resp.text = f"hi {name}"

    assert client.get("http://testserver/sauron").text == "hi sauron"

Templates

The default folder for templates is templates. You can change it when initializing the main API() class:

app = API(templates_dir="templates_dir_name")

Then you can use HTML files in that folder like so in a handler:

@app.route("/show/template")
def handler_with_template(req, resp):
    resp.html = app.template(
        "example.html", context={"title": "Awesome Framework", "body": "welcome to the future!"})

Static Files

app = API(static_dir="static_dir_name")

Then you can use the files inside this folder in HTML files:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>

    <link href="/static/main.css" rel="stylesheet" type="text/css">
</head>

<body>
    <h1>{{body}}</h1>
    <p>This is a paragraph</p>
</body>
</html>

Middleware

You can create custom middleware classes by inheriting from the bumbo.middleware.Middleware class and overriding its two methods that are called before and after each request:

from pylord.app import PyLordApp
from pylord.middleware import Middleware


app = PyLordApp()


class SimpleCustomMiddleware(Middleware):
    def process_request(self, req):
        print("Before dispatch", req.url)

    def process_response(self, req, res):
        print("After dispatch", req.url)


app.add_middleware(SimpleCustomMiddleware)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pylord-0.2.4.tar.gz (12.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pylord-0.2.4-py3-none-any.whl (8.6 kB view details)

Uploaded Python 3

File details

Details for the file pylord-0.2.4.tar.gz.

File metadata

  • Download URL: pylord-0.2.4.tar.gz
  • Upload date:
  • Size: 12.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.10.11

File hashes

Hashes for pylord-0.2.4.tar.gz
Algorithm Hash digest
SHA256 c4f336f11be6f668e409fabeef559c311730bcf4d21c3893bd89bd3ab51644ab
MD5 33752c7a7cfcb0437235fa90e7e102d9
BLAKE2b-256 96d86935c1d38a23d570ccbfefd0ca9c50a3c367e32eb41d45ef146fe83da6e3

See more details on using hashes here.

File details

Details for the file pylord-0.2.4-py3-none-any.whl.

File metadata

  • Download URL: pylord-0.2.4-py3-none-any.whl
  • Upload date:
  • Size: 8.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.10.11

File hashes

Hashes for pylord-0.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 da4278dede9684fe1972155be99979a4d69d93079668936eb2de6620b6e534b8
MD5 6ff22a1730dbf8721a7b4f3283f5cc8f
BLAKE2b-256 5ee0d7644713830ab65fa24bc44f695f87fbd96894a9bd4462a073a72833ebd2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page