Thread: Web Framework

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    74
    Rep Power
    12

    Web Framework


    Hello,

    I am trying to teach myself one of the simpler web framework namely Bottle or Flask. I have tried Django but found it to be really complicated. Flask / Bottle seems to me slightly smaller and easier to learn, but there is one barrier that I just can not overcome and it appears right in the beginning of the tutorial "decorators". I have looked at some explanations or examples and just can not get what they are or how to use them. The only think that I do understand is that you are passing a function to another function which can modify the original one.

    Could someone please explain with simple example how to write and use one.

    Thank you.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,901
    Rep Power
    481
    The j language has adverbs as a part of speech. Adverbs modify verbs. Decorators are a similar concept. Apparently I can still write a decorator, see below. If you actually test and examine the result from this code you'll see that the decorator runs when the module is imported.

    We know that the decorator must return a callable, and that
    Code:
    @dec2
    @dec1
    def func(arg1, arg2, ...):
        pass
    
    #is equivalent to:
    
    def func(arg1, arg2, ...):
        pass
    func = dec2(dec1(func))
    Decorator examples, the first of which even I can understand.

    Code:
    # passes doctest
    # $ python3 -m doctest -v NAME_OF_THIS_FILE.py
    
    def offset(function):
        print('the offset function ran with argument %s'%str(function))
        def f(self,item):
            return function(self,item-self.QuadIO)
        return f
    
    class LIST(list):
        '''
            list with offset index origin.
            >>> LIST('abc',1)[1]   ########<<<<=== HERE this is the purpose of the class
            'a'
        '''
        def __init__(self,iterable,index_origin=0):
            list.__init__(self,iterable)
            self.QuadIO = index_origin
    
        @offset
        def __getitem__(self,item):
            return list.__getitem__(self,item)
    I can't describe this better than the various PEPs. Find the PEP index at python.org. Search for decorator. Read them til yer ill.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    74
    Rep Power
    12
    Thank you, I just guess there are some things that are so way above you that no matter how much you try you will not get.
    So I guess that you can not learn a simple framework if you dont get that. I thought that flask and bottle are supposed to be simple ones??

    You know there are a couple of things for which I could not find any easy to understand tutorials. I do have a basic understanding of classes but have not found any tut on what are so called magic methods or how to use them in simple terms. I dont mean simple one like __init__ but all others which are used everywhere.

    Thank you once again regarding decorators, I guess its just not for me to get a grasp.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,901
    Rep Power
    481
    What is a magic method? Name a few. Name three, as my sixth grade social studies teacher demanded.

    Here's another decorator example.
    Code:
    import pprint
    
    def debug(function):
        name = str(function).split()[1]
        print('Enunciate function %s.'%name)
        def debugged(*args,**kwargs):
            print('{Calling %s(*%s,**%s)'%(
                name,pprint.pformat(args),pprint.pformat(kwargs)))
            result = function(*args,**kwargs)
            print('result %s}'%pprint.pformat(result))
            return result
        return debugged
    
    @debug
    def piglatin(word):
        try:
            if 2 < len(word):
                return word[1:]+word[0]+'ay'
        except:
            pass
        return word
    
    def square(n):
        return n*n
    
    
    print(piglatin('pig'))
    print(piglatin(word='latin'))
    
    
    print(square(16))
    Now, even if you don't understand what the devil's going on you import this debug function into your name space, and you can get insight into functions you're having trouble with merely by writing @debug on the source line before your function definition. Without making any other changes in your program every time that function is called your output will include a message telling you the functions name, its arguments, and the output.
    Code:
    @debug
    def confusing(many,arguments):
        #computations and logic
        return result or None
    Firstly, you can use decorators without understanding how they work. Oh---be sure not to use the decorator that emails me your country personal identification number.

    Secondly, you can understand decorators. Run the program. Make a tiny change. Run the program again. How did the output change? Don't understand pprint.pformat ? Look it up in the python library documents. Don't understand **kwargs? Hunt for passing a dictionary as the key word arguments in a function call.


    Code:
    $ python3 p.py
    Enunciate function piglatin.
    {Calling piglatin(*('pig',),**{})
    result 'igpay'}
    igpay
    {Calling piglatin(*(),**{'word': 'latin'})
    result 'atinlay'}
    atinlay
    256
    I ran the program above. First it prints Enunciate... That comes from the execution of debug in the decorator. How do I know? I suppose a clever person would use pdb but I'm not, so I put print statements in the code and run it again:
    Code:
    #...
    print('using my decorator')
    @debug
    def piglatin(word):
        try:
            if 2 < len(word):
                return word[1:]+word[0]+'ay'
        except:
            pass
        return word
    print('decorated!')
    #...
    Don't understand how piglatin works? Try it alone. Use non-string arguments. Use short string arguments. (hahaha I didn't make any of these tests...)
    Last edited by b49P23TIvg; November 8th, 2012 at 12:46 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    74
    Rep Power
    12
    Magic Methods as they are called __xxx__.

    For example, i see quite frequently something like this: cls.__mro__ what is that?

    Regarding magic methods its something like this:

    Code:
    >>> dir('hello')
    ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__',
    How do you use them, why, where

    Thanks once again
  10. #6
  11. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,901
    Rep Power
    481
    Code:
    '''
        $ python3 p.py
        invoke my_string.__add__
        hello world!
    
        invoke my_string.__len__
        5
    
        (<class '__main__.my_string'>, <class 'str'>, <class 'object'>)
    '''
    
    class my_string(str):
    
        def __len__(self):
            print('invoke my_string.__len__')
            return str.__len__(self)
    
        def __add__(self,other):
            print('invoke my_string.__add__')
            return my_string(str.__add__(self,other))
    
    
    hi = my_string('hello')
    print(hi + ' world!')
    print('')
    print(len(hi))
    print('')
    print(my_string.__mro__)
    my_string('hello') calls a constructor to make this object. Which __init__ did it use? When looking for __init__ the method resolution order says: "first look in my_string, then look in str, finally look in object". my_string hasn't got an __init__; str has an __init__; python builds str.__init__ to construct the my_string object.

    In hi + ' world!' the + operator tells python to hunt for an __add__ method. Using the __mro__ it finds a definition in class my_string and uses that definition. That method, as you can tell by looking at it, prints a message and then explicitly calls str.__add__ to finish the job. And then I decided that the result type should be my_string instead of str, and that's why I stuck the expression inside my_string(string_object).

    What about len(hi)? len looks for an object's __len__ method. It finds one in my_string. I programmed it to behave corresponding to __add__ .

    There are a whole lot of these, some of which changed name between python 2 and 3, some make iterators work, some are used to implement context (with statement), there's a yield statement, a next() functions, all the operators left and right.

    Thankfully you can't also change operator precedence in these nasty languages (C++, python, and the like). a*b+c evaluates
    (a.__mul__(b)).__add__(c)


    j doesn't overload operators, the only data structure is array, and sentences of verbs and nouns evaluate from right to left. j is easier.
    [code]Code tags[/code] are essential for python code and Makefiles!
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    74
    Rep Power
    12
    hi,

    I would like to say, that i am very grateful for the time you took to try to explain and answer my questions, but now I understand why I could not understand this subject matter it is way above my head.

    lol I love python and feel that it is a great language and I felt that I could even attempt to look for an entry level job using python, but hey that feeling just passed.
  14. #8
  15. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,901
    Rep Power
    481
    dude or dudette I can't find a python job either. Then again, internet/database/gui programming aren't my strengths.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo