Skip to main content

Python library helps optimize Flask development to be flexible and object-oriented.

Project description

TJFU

Python library helps optimize Flask development to be flexible and object-oriented.

Extensions have been integrated

  1. JWT
  2. SocketIO
  3. Limiter

Installation

pip install tjfu

Get started

Basic example:

from os import path
from tjfu import TJFU
from datetime import timedelta

HERE = path.abspath(path.dirname(__file__))

def error_404(error):
    return "Not Found!!!", 404

def error_500(error):
    return "Error!!!", 500

"""
    The TJFU configuration must be placed
    at the beginning of the main function.
    Absolutely do not define or import any Route
    before calling the build() function because an error may occur.
"""
{
TJFU
    .host_name("0.0.0.0") # required
    .host_port(3100) # required        
    .root_path(HERE) # optinal (default: '.')        
    .template_folder("templates") # optinal (default: 'templates')
    .static_folder("static") # optinal (default: 'static')
    .jwt_secret_key("your_jwt_secret_key")
        # optinal / enter value if you want to use JWT, 
        # Otherwise the jwt_required function will throw an error
    .jwt_access_token_expires(timedelta(days=7)) # optinal (default: 'timedelta(days=7)')
    .jwt_refresh_token_expires(timedelta(days=14)) # optinal (default: 'timedelta(days=14)')
    .socket_root("socket") # optinal (default: 'socket') 
    .ignore_cors(True) # optinal (default: 'True')
    .add_error_handler(404, error_404) # optional
    .add_error_handler(500, error_500) # optional
    .add_status_code_handler(500, error_500) # optional (>=3.2.0)
    .limiter_storage_uri("memory://") # optinal (default: 'memory://')
    .default_limits(["200 per day", "50 per hour"]) # optinal (default: '[]')
    .log_output(False) # optinal (default: 'True')
    .debug(False) # optinal (default: 'True')
    .use_reloader(False) # optinal (default: 'True')
    .allow_unsafe_werkzeug(False) # optinal (default: 'True')
    .app_config('MY_SECRET_KEY', 'my_secret_key') # optional (>=3.2.0): use as app.config['MY_SECRET_KEY'] = 'my_secret_key'
    .app_config('MY_SECRET_KEY_2', 'my_secret_key') # optional (>=3.2.0): use as app.config['MY_SECRET_KEY_2'] = 'my_secret_key'
    .build()
}

from tjfu import Route

app = TJFU.init_app(Route("index", "/"))

IS_PRODUCTION = False

if __name__ == "__main__":
    if IS_PRODUCTION:
        app.run()
    else:
        TJFU.run()

Define a Custom Route:

# OTHER CODE...
from tjfu import Route, SimpleRenderTemplateRoute

class MyCustomRoute(Route):
    def __init__(
        self,
        your_name: str
    ):
        super().__init__("mycustomroute", "/mycustomroute")
        self._your_name = your_name
    
        self._blueprint.route('/')(self._index) # /mycustomroute
        self._blueprint.route('/jwt')(self._jwt) # /mycustomroute/jwt
        self._blueprint.route('/class_variable')(self._class_variable) # /mycustomroute/class_variable
        self._blueprint.route('/limiter')(self._limiter) # /mycustomroute/limiter
    
    # Basic route function
    @staticmethod
    def _index():
        return "Hello World!"
    
    # JWT route function
    @staticmethod
    @jwt_required()
    def _jwt():
        return "Hello From JWT!"
    
    
    # Class variable route function
    def _class_variable(
        self
    ):
        return f"Hello {self._your_name}!"
    
    # Limiter route function
    @staticmethod
    @TJFU.limiter().limit('1/second')
    def _limiter():
        return "Hello from Limiter!"
    

index_route = Route("index", "/")
my_custom_route = MyCustomRoute("John Doe")
another_my_custom_route = MyCustomRoute("Lisa")

# /mycustomroute
index_route.register_route(my_custom_route)

"""
    You can easily define a route to
    render an HTML file
    using the SimpleRenderTemplateRoute class
"""
# /my_html_file
index_route.register_route(
    SimpleRenderTemplateRoute(
        "my_html_file",
        "/my_html_file",
        "my_html_file.html"
    )
)

# /mycustomroute/mycustomroute
my_custom_route.register_route(another_my_custom_route)

# You must register routes and sockets before calling the init_app function
app = TJFU.init_app(index_route)

# OTHER CODE...

Register Routes using Dictionary (>=3.1.0):

# OTHER CODE...

app = TJFU.init_app(
    Route("index", "/"), 
    {
        Route("api", "/api"):{
            
            Route("v1", "/v1"):{
                
                Route("user", "/user"):{
            
                }    
                
            }
            
        },
        Route("tool", "/tool"):{
            SimpleRenderTemplateRoute(
                "my_tool",
                "/my_tool",
                "my_tool.html"
            )
        },
        SimpleRenderTemplateRoute(
            "hello_world",
            "/hello_world",
            "hello_world.html"
        ): None
    }
)

# OTHER CODE...

Get Flask App after TJFU.build() (>=3.2.0)

# Example
from tjfu import TJFU
from flask_mail import Mail, Message
mail = Mail(TJFU.app())

Get Extensions (JWT/Limiter/SocketIO) after TJFU.build() (>=3.3.0)

TJFU.jwt()
TJFU.limiter()
TJFU.socketio()

Add custom extensions to TJFU after TJFU.build() (>=3.3.0)

# OTHER CODE...

from flask_mail import Mail, Message
mail = Mail(TJFU.app())

TJFU.add_extension(
    'send_mail',
    mail
) 

app = TJFU.init_app(index_route)

# OTHER CODE...

And then you can take it out and use it in contexts (e.g. Route)

mail = TJFU.get_extension('send_mail')

Define a Socket Handle:

# OTHER CODE...

from tjfu import SocketEvent, SocketHandle
from flask import request
class MySocketHandle(SocketHandle):
    def __init__(self):
        super().__init__(self._my_handle)
        
    def _my_handle(self, msg):
        print(f"Client id: {request.sid}")
        print(f"Msg from client: {msg}")
        TJFU.emit(
            SocketEvent("chat", "send"),
            "Hello client from socket handle!!!"
        )
        
TJFU.register_socket_event(
    SocketEvent("chat", "send"),
    MySocketHandle()
) 

app = TJFU.init_app(index_route)

# OTHER CODE...

You can send data to the client via Socket in places outside the Socket Handle context (such as Route) through the TJFU.no_context_emit function

class SendMsgRoute(Route):
    def __init__(
        self
    ):
        super().__init__("send_msg", "/send_msg")
        self._blueprint.route('/')(self._index)
        
    @staticmethod
    def _index():
        TJFU.no_context_emit(
            SocketEvent("chat", "send"),
            "Hello client from route!!!"
        )
        return "Hello World!"

Simple HTML code to receive and send data from Socket

<!DOCTYPE html>
<html>
<head>
    <title>Socket.IO Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script>
    <script type="text/javascript">
        var socket = io('http://0.0.0.0:3100/socket/chat');
        socket.on('connect', function () {
            console.log('Connected to the server');
        });
        socket.on('send', function (data) {
            console.log('Message received: ' + data);
        });
        socket.on('disconnect', function () {
            console.log('Disconnected from server');
        });
        function sendMessage() {
            var message = document.getElementById('message').value;
            socket.emit('send', message);
        }
    </script>
</head>

<body>
    <h1>Socket.IO Example</h1>
    <input type="text" id="message" placeholder="Enter message">
    <button onclick="sendMessage()">Send</button>
</body>

</html>

Changelog

  • 1.0.0: First version released. There is a problem in Socket implementation.
  • 2.0.0: Edit the Socket structure. There is a problem deploying the application to the production environment.
  • 3.0.0: The version is relatively stable, overcoming the problem of deploying applications in production environments.
  • 3.1.0: Added the function of registering Routes using Routes Map
  • 3.1.1: Fixed an issue where additional variables could not be added when inheriting the _index function in Route.
  • 3.2.0: Assign keys/values to Flask App Config using TJFU.app_config(...,...), add function TJFU.app() to get Flask App after calling TJFU.build(), use the add_status_code_handler function instead of the add_error_handler function.
  • 3.3.0: Build functions that take instances of extensions and add custom extensions.

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

tjfu-3.3.0.tar.gz (9.9 kB view details)

Uploaded Source

Built Distribution

tjfu-3.3.0-py3-none-any.whl (8.0 kB view details)

Uploaded Python 3

File details

Details for the file tjfu-3.3.0.tar.gz.

File metadata

  • Download URL: tjfu-3.3.0.tar.gz
  • Upload date:
  • Size: 9.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.10.12

File hashes

Hashes for tjfu-3.3.0.tar.gz
Algorithm Hash digest
SHA256 8d13650ef5a0f2bb93c1b96e43b5f8d09ebccd99ebabce3b31bd6e29ccd97190
MD5 18b72ee82190429952839feb3ea2a8ae
BLAKE2b-256 b2af7e013d284b2dab79ed3663e387fe7ff8b0da1cba8726a73d8fb58f7e0ed9

See more details on using hashes here.

File details

Details for the file tjfu-3.3.0-py3-none-any.whl.

File metadata

  • Download URL: tjfu-3.3.0-py3-none-any.whl
  • Upload date:
  • Size: 8.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.10.12

File hashes

Hashes for tjfu-3.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 735c72d6b45a563bd31d0057834f3acd11b22c8a09b6a064f5c381da5b59bce9
MD5 45419a159fcf8358650965b960d04b0c
BLAKE2b-256 24974f70a51672a06fac715dbed53536e8ff2ed64c41f39e0721a9b2bb994859

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