简体   繁体   English

Python Flask:具有多个定义或将所有内容存储在字典中

[英]Python Flask: Having multiple definitions or storing everything in a dictionary

I currently have something like this我目前有这样的东西

def get_graphnet_medication_issued(detail_id):
    """
    Getting the Graphnet issued medication
    """
    data = get_graphnet_api_request(detail_id,'/gp/patients/','/gp-medications/issued')
    return data

def get_graphnet_medication_repeat(detail_id):
    """
    Getting the Graphnet repeat medication
    """
    data = get_graphnet_api_request(detail_id,'/gp/patients/','/gp-medications/repeat')
    return data

For each REST API call we can make, we do a new 'def' which is all well and good for the dozen or so we have but I started to think about scalability and what would happen if we had hundreds对于我们可以进行的每个 REST API 调用,我们都会执行一个新的“def”,这对于我们拥有的十几个来说都很好,但我开始考虑可扩展性以及如果我们有数百个会发生什么

Would putting the values in a dict be any better?将值放在dict中会更好吗?

endpoints = {
    "issued":{
        "pre":"/gp/patients/",
        "post":"/gp-medications/issued"
    },
    "repeat":{
        "pre":"/gp/patients/",
        "post":"/gp-medications/repeat"
    },
    "random":{
        "pre":"/a/b/c/d",
        "post":"/e/f/g/h"
    }
}

Then calling然后打电话

get_graphnet_api_request(detail_id,'issued')

Then within that def reference the dictionary and the necessary keys/values?然后在那个def中引用字典和必要的键/值?

Please note that the values of pre and post can differ dramatically.请注意, prepost的值可能会有很大差异。 In the above, it just so happens they are very similar.在上面,恰好它们非常相似。

Which way would be deemed as more scalable?哪种方式被认为更具可扩展性? Is there another better way?还有其他更好的方法吗? I now if we're going to have hundreds it's going to be a large amount of work anyway but just thought storing them in a dict might be better我现在如果我们要有数百个,无论如何都会有大量的工作,但只是认为将它们存储在dict中可能会更好

Sure, there are many ways to DRY that code.当然,有很多方法可以DRY该代码。 The dict approach is very sensible. dict 方法非常明智。 But it can also be sensible to have each call as a separate function to aid discoverability.但是,将每个呼叫作为一个单独的 function 来帮助发现也是明智的。 So as an alternative, use a function factory function:因此,作为替代方案,使用 function 工厂 function:

def graphnet_medication(pre, post):
    def get_graphnet_medication(detail_id):
        return get_graphnet_api_request(detail_id, pre, post)
    
    return get_graphnet_medication


get_graphnet_medication_issued = graphnet_medication('/gp/patients/', '/gp-medications/issued')
get_graphnet_medication_repeat = graphnet_medication('/gp/patients/', '/gp-medications/repeat')
...

This is basically a specialised version of partial .这基本上是partial的特殊版本。 Maybe do some combination of both approaches.也许将这两种方法结合起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM