FlASK中的endpoint問題


先貼一點有關的flask代碼,時間有限,我慢慢擴充

以下是flask源碼中app.py中add_url_rule的代碼。

主要是view_func  -- endpoint -- url 之間的對應關系。

flask中,view_func與url並不是直接對應的,是url先找到endpoint, 然后通過endpoint再去找到對應的view_func,一個endpoint只能對應於一個view_func,在注冊add_url_rule的時候,如果不指定endpoint,那么endpoint就會默認為函數名字,如果同一個endpoint於多個url注冊的話,會有問題,詳見代碼中,會判斷之前已經對應到的跟現在是不是一個,如果不是的話,那么就要拋出異常。然后再去訪問這些url當然是肯定不行的啦。有時間會慢慢擴充這部分的內容。

 1     @setupmethod
 2     def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
 3         if endpoint is None:
 4             endpoint = _endpoint_from_view_func(view_func)
 5         options['endpoint'] = endpoint
 6         methods 
 7        if methods is None:
 8             methods = getattr(view_func, 'methods', None) or ('GET',)
 9         if isinstance(methods, string_types):
10             raise TypeError('Allowed methods have to be iterables of strings, '
11                             'for example: @app.route(..., methods=["POST"])')
12         methods = set(item.upper() for item in methods)
13 
14         required_methods = set(getattr(view_func, 'required_methods', ()))
15 
16         provide_automatic_options = getattr(view_func,
17             'provide_automatic_options', None)
18 
19         if provide_automatic_options is None:
20             if 'OPTIONS' not in methods:
21                 provide_automatic_options = True
22                 required_methods.add('OPTIONS')
23             else:
24                 provide_automatic_options = False
25 
26         # Add the required methods now.
27         methods |= required_methods
28 
29         rule = self.url_rule_class(rule, methods=methods, **options)
30         rule.provide_automatic_options = provide_automatic_options
31 
32         self.url_map.add(rule)
33         if view_func is not None:
34             old_func = self.view_functions.get(endpoint)
35             if old_func is not None and old_func != view_func:
36                 raise AssertionError('View function mapping is overwriting an '
37                                      'existing endpoint function: %s' % endpoint)
38             self.view_functions[endpoint] = view_func

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM