读写文本fi

2024-04-26 14:31:17 发布

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

我正在写一个项目,目标是用Django构建一个类似于管理层(业务管理,怎么说)的东西。你知道吗

实际上,我需要一个全局变量的支持,因为产品由一个递增的代码标识,有时我会重置它(它不是主键,只是我用来工作的代码)。 因此,为了避免使用全局变量(也是由于服务器重新启动时我在代码中遇到的问题),我想在文本文件中编写实际的代码。你知道吗

使用save方法重写时,我保留写入该文件的数字,并使用它填充产品代码字段。然后我增加文件中写入的数字并关闭它。这样,我只需要在文件中用文本编辑器写“0”(零)来重置che代码!如果服务器重新启动,我不会像使用其他方法一样丢失实际的数字(例如:保存在缓存中的变量)

我遇到的错误是:没有名为product的文件/目录_代码.txt你知道吗

下面是模型的代码:

class Product(models.Model):

    code = models.AutoField(primary_key=True, editable=False)
    #category = models.ForeignKey(Category)

    product_code = models.IntegerField(editable=False, blank=True, null=True, verbose_name="codice prodotto")

    description = models.CharField(max_length=255, verbose_name="descrizione")
    agreed_price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="prezzo accordato")
    keeping_date = models.DateField(default=datetime.date.today(), verbose_name="data ritiro")

    selling_date = models.DateField(blank=True, null=True, verbose_name="data di vendita")
    discount = models.SmallIntegerField(max_length=2, default=0, verbose_name="sconto percentuale applicato")
    selling_price = models.DecimalField(
        max_digits=5, decimal_places=2, blank=True, null=True, verbose_name="prezzo finale"
    )
    sold = models.BooleanField(default=False, verbose_name="venduto")

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):

        if self.product_code is None:
            handle = open('product_code.txt', 'r+')
            actual_code = handle.read()
            self.product_code = int(actual_code)
            actual_code = int(actual_code) + 1  # Casting to integer to perform addition
            handle.write(str(actual_code))  # Casting to string to allow file writing
            handle.close()

        if self.sold is True:
            if self.selling_date is None or "":
                self.selling_date = datetime.date.today()
            if self.selling_price is None:
                self.selling_price = self.agreed_price - (self.agreed_price/100*self.discount)

        super(Product, self).save()

    class Meta:
        app_label = 'business_manager'
        verbose_name = "prodotto"
        verbose_name_plural = "prodotti"

文件product_code.txt位于models.py的同一目录中 我确保错误是指代码行

handle = open('product_code.txt', 'r+')

因为我和调试器核对过了。你知道吗

有什么办法解决这个问题吗?谢谢


Tags: 文件代码nameselfnonefalsetrueverbose
1条回答
网友
1楼 · 发布于 2024-04-26 14:31:17

您应该以append模式打开文件:

with open('product_code.txt', 'a') as handle:
    ...

但我会考虑使用另一种方法(可能是数据库),除非你从一开始就知道你不会看到任何竞争条件。你知道吗

相关问题 更多 >