Skip to main content

No project description provided

Project description

Flask-PydanqlAPI

Overview

Flask-PydanqlAPI is a Flask extension that offers seamless integration with the Pydanql library, simplifying interactions with PostgreSQL databases. This extension automates the generation of RESTful API endpoints for your database models, offering optional features like JWT authentication and query filtering.

⚠️ Early Version Warning: This is an early version of the Flask-PydanqlAPI extension and is subject to changes. Although it is fully functional, future versions may introduce breaking changes. Your feedback is highly appreciated!

Features

  • Simple CRUD operations through Pydanql models
  • Optional JWT Authentication
  • Customizable query and return fields
  • Optional support for additional filtering on queries

Getting Started

Basic Setup

Here's a minimal example to show how to set up the Flask-PydanqlAPI extension without authentication and custom filtering.

# Easily create a full-fledged API with all CRUD actions. Create, Read, Update
# and Delete. Advanced search options, extensible, and even many more.
# 
# GET Books from /books/find?year__range=1950,1960&title__like=Lord

from flask import Flask
from flask_pydanql_api import PydanqlAPI, Endpoint
from pydanql.model import ObjectBaseModel

app = Flask(__name__)

# Define youre Model 
class Book(ObjectBaseModel):
    title: str
    author: str
    year: int

# Define youre API-Endpoint
class Books(Endpoint):
    slug = 'books'
    model = Book

# Connect to your postgreSQL Database
app.config['PYDANQL_API_DB'] = { 'database': ..., 'user': ..., 'password': ... }
app.config['PYDANQL_API_ENDPOINTS'] = [Books]

PydanqlAPI(app)

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

Advanced Setup with JWT and Filtering

Here's an example that includes JWT authentication and custom filtering.

from flask import Flask, request, jsonify
from flask_pydanql_api import PydanqlAPI, Endpoint
from pydanql.model import ObjectBaseModel
from pydanql.table import Table
from datetime import datetime
from flask_jwt_extended import create_access_token, verify_jwt_in_request, get_jwt_identity

class Car(ObjectBaseModel):
    brand: str
    model: str
    year: int
    color: str
    miles: float
    owner: str

    def miles_per_year(self):
        current_year = datetime.now().year
        years_since_manufacture = current_year - self.year + 1
        return float(self.miles / years_since_manufacture)

    def description(self):
        return f"A {self.color} {self.model} build by {self.brand}"


class Cars(Endpoint):
    slug = 'cars' # part of the url to accesse the table 
    model = Car # The object for table entries
    allowed_query_fields = ['brand', 'color', 'year', 'owner']
    visible_fields = ['owner', 'brand', 'color', 'year', 'model', 'slug', 'miles_per_year', 'description']

    @staticmethod
    def _filter(query_type, query_table):
        verify_jwt_in_request()
        current_user = get_jwt_identity()
        if query_type == 'find':
            return {'owner': current_user}
        if query_type == 'get':
            return {'owner': current_user}
        if query_type == 'create':
            return {'owner': current_user}
        if query_type == 'delete':
            return {'owner': current_user}

        return jsonify({'error': 'Not todo', 'detail': 'todo'}), 405


app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret'
app.config['PYDANQL_API_DB'] = {
    'database': 'testdb',
    'user': 'testuser',
    'password': 'testpass',
    'host': 'localhost',
    'port': '5432'
}
app.config['PYDANQL_API_ENDPOINTS'] = [Cars]

PydanqlAPI(app)

@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)

    # In a real-world app, you'd validate these credentials against a database
    if password != 'password':
        return jsonify({'login': False}), 401

    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token), 200

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

Contributing

We are open to contributions. Please fork the repository and submit your pull requests!

License

Flask-PydanqlAPI is licensed under the MIT license.

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

Flask-Pydanql-API-0.0.2a0.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

Flask_Pydanql_API-0.0.2a0-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file Flask-Pydanql-API-0.0.2a0.tar.gz.

File metadata

  • Download URL: Flask-Pydanql-API-0.0.2a0.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for Flask-Pydanql-API-0.0.2a0.tar.gz
Algorithm Hash digest
SHA256 055574f6ee7bcb9e2667956ae92c8093320463178a325dc914f0ed67323400e8
MD5 c1dcb76e7af66cc9b55b8429cd76d036
BLAKE2b-256 3f4dbcd1d8c52fa544f7012031cde323953655fa526231611abccd15711c1196

See more details on using hashes here.

File details

Details for the file Flask_Pydanql_API-0.0.2a0-py3-none-any.whl.

File metadata

File hashes

Hashes for Flask_Pydanql_API-0.0.2a0-py3-none-any.whl
Algorithm Hash digest
SHA256 70a6c4a59c4823cc01c5dc2838832ed6b97ac5fea4004798befefbd72f9dc4dd
MD5 33330608c46198b4c4273719cecc1e18
BLAKE2b-256 d95854b9818fa7a6a33ab12e4e85ed5f7067bfd1b79ec205669e02f99bb13447

See more details on using hashes here.

Supported by

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