Skip to main content

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.

Metadata

Release files for tjfu 3.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tjfu 3.3.0
File Size Uploaded Provenance Actions
tjfu-3.3.0.tar.gz 9.9 kB Without provenance Details for tjfu-3.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tjfu 3.3.0
File Interpreter ABI Platform Actions
tjfu-3.3.0-py3-none-any.whl Python 3 none any Details for tjfu-3.3.0-py3-none-any.whl

Total release size: 17.9 kB

Release files / tjfu-3.3.0.tar.gz

Download URL tjfu-3.3.0.tar.gz
Size 9.9 kB
Tags Source
SHA-256 checksum
How to use checksums
8d13650ef5a0f2bb93c1b96e43b5f8d09ebccd99ebabce3b31bd6e29ccd97190
BLAKE2b-256 checksum
How to use checksums
b2af7e013d284b2dab79ed3663e387fe7ff8b0da1cba8726a73d8fb58f7e0ed9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.10.12

Release files / tjfu-3.3.0-py3-none-any.whl

Download URL tjfu-3.3.0-py3-none-any.whl
Size 8.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
735c72d6b45a563bd31d0057834f3acd11b22c8a09b6a064f5c381da5b59bce9
BLAKE2b-256 checksum
How to use checksums
24974f70a51672a06fac715dbed53536e8ff2ed64c41f39e0721a9b2bb994859
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.10.12

Security for tjfu 3.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page