googleappengine Python Datetime成本比较与字符串比较

2024-09-29 22:33:26 发布

您现在位置:Python中文网/ 问答频道 /正文

希望我能在这里清楚地表达自己,忍受我

假设我有一个销售t恤衫的零售应用程序。每件t恤衫都可以处于预售阶段,也可以处于销售阶段

每次用户进入特定的t恤页面时,我都可以比较datetime now和它上市的日期time,确定它是预售还是在售,并输出适当的数据/内容

相反,我可以在我的t恤上有一个“phase”字符串属性,最初设置为“presale”。然后,我可以设置一个任务队列以在销售开始时执行,并将t恤的“phase”属性从“presale”切换到“in sale”。当用户访问t恤页面时,我检查字符串,不管它是“presale”还是“insale”,并输出适当的数据/内容

我的问题是,一种方法比另一种更可取吗?我假设第一个方法是datetime计算/比较,比第二个基于字符串比较的方法效率低?但是,第二种方法需要使用任务队列,这会增加开销/成本


Tags: 数据方法字符串用户应用程序内容datetime属性
1条回答
网友
1楼 · 发布于 2024-09-29 22:33:26

我首先想到的是配置。它是本地的,它只是读取一个文件,它不比较任何东西

好的,我会用一个我在Django和Flask项目中经常用到的结构。我的文件夹结构通常如下所示:

main/
 -app/
   |_ __init__.py
   |_ app.py
 -templates/
 -settings/
   |_ __init__.py
   |_ settings.py
   |_ settings.json
_ main.py

My settings.py文件是变量所在的位置。它的价值是巨大的,但它的实现很简单。 我们来看一个例子:

#settings.py
import json
path_of_json= "path here"
class Settings:
#Object interface of the settings

    class _Product:
    # Non-public class that implements a object interface for the products

        def __init__(self,name,sale_status):
        # Inicialization
        self.name = name
        self.sale_status = sale_status


    def __init__(self):
    #Handles what happens at initialization
        global path_of_json
        self.dict= self._load_json(path_of_json)  #this dictionary will hold the data we load from the JSON
        self.product1 = self._Product(self.dict['product1_name'],self.dict['product1_sale_status'])
        #Here we use the data that were loaded from the JSON
        self.product2 = self._Product(self.dict['product2_name'],self.dict['product2_sale_status'])
    def _load_json(self):
        #Here you implement the JSON loading
        pass

这是我们的配置文件

现在到主应用程序,以及如何使它做一些事情

#main.py
from settings.settings import Settings

my_settings = Settings()
product1 = { "name":my_settings.product1.name,"sale_status":my_settings.product1.sale_status}
#Here the product was loaded from the settings
#A lot of awesome code here


def render_product_page(product):  #This function receives a dictionary
    render_template("sale_status-insert how your template engine show fields here", product["name"])

事情就是这样做的

现在,您只需要实现一个每24小时唤醒一次的小守护进程,检查settings.json文件上的数据,如果数据过时,请更新它(这个我会留给你XD)

希望这有帮助:)

相关问题 更多 >

    热门问题