Home>

In a number of modules, the python functions are caused by a fragible method, I suppose with the help of the decorator. (A list of such modules that I know: Django. . Flask. . Aiogram . Pyrogram . Discord.py. ) The code will be shown on the Flask example

from Flask Import Flask, Request
App= Flask (__ Name__)
@ app.route ('/')
DEF index ():
    Return 'Heya'
IF __name__== "__main__":
    App.Run (Host= '0.0.0.0', port= 80)

Flask independently causes poundation index. Having only a decorator. How to make something similar?

  • Answer # 1

    Well, I taking a typical decorator for 10 minutes in 10 minutes analogue sketched:

    Class WebServer:
        Def __init __ (Self):
            self.doit= ​​{}
        DEF ROUTE (SELF, PATH):
            Def Decorator (Function):
                self.doit [Path]= Function
            Return Decorator
        DEF RUN (SELF):
            Print ('Server Is Running')
            For i, Key in Enumerate (Self.Doit):
                Print (I, Key)
                self.doit [Key] ()
    App= WebServer ()
    @ app.route ('/')
    DEF index ():
        PRINT ('GO GO GO!')
    @ app.route ('/img')
    deframes ():
        Print ('images!')
    IF __name__== "__main__":
        app.run ()
    

    Conclusion:

    Server Is Running
    0 /
    GO GO GO!
    1 /IMG.
    Images!
    

    update : a little complicated code, you can prescribe a lot Route. They dig into a dictionary that can then be sorted out.

  • Answer # 2

    Well, I taking a typical decorator for 10 minutes in 10 minutes analogue sketched:

    Class WebServer:
        Def __init __ (Self):
            self.doit= ​​{}
        DEF ROUTE (SELF, PATH):
            Def Decorator (Function):
                self.doit [Path]= Function
            Return Decorator
        DEF RUN (SELF):
            Print ('Server Is Running')
            For i, Key in Enumerate (Self.Doit):
                Print (I, Key)
                self.doit [Key] ()
    App= WebServer ()
    @ app.route ('/')
    DEF index ():
        PRINT ('GO GO GO!')
    @ app.route ('/img')
    deframes ():
        Print ('images!')
    IF __name__== "__main__":
        app.run ()
    

    Conclusion:

    Server Is Running
    0 /
    GO GO GO!
    1 /IMG.
    Images!
    

    update : a little complicated code, you can prescribe a lot Route. They dig into a dictionary that can then be sorted out.