简体   繁体   English

读写文本文件

[英]reading and writing text file

I'm writing a project with the goal to build something like a managerial (business management, how to say), using Django. 我正在编写一个项目,目标是使用Django构建类似管理(业务管理,怎么说)的内容。

Actually, i need the support of a global variable because products are identified by an increasing code, that sometime i reset ( it is NOT the primary key, just a code i use to work ). 实际上,我需要一个全局变量的支持,因为产品是由不断增加的代码标识的,有时我会对其进行重置( 这不是主键,只是我用来工作的代码 )。 So, to avoid the usage of a global variable, also due to problem i would incour if the server reboots, i'd like to write the actual code on a text file. 因此,为避免使用全局变量,同样由于问题,如果服务器重新启动,我会感到烦恼,我想在文本文件上写入实际代码。

With a save method overriding i keep the number written in this file and i use it to fill the product code field. 使用覆盖的保存方法时,我将数字保留在此文件中,并用它来填写产品代码字段。 Then i increase the number written in the file and close it. 然后,我增加写入文件的数量并关闭它。 This way, i just need to write "0" (zero) with a text editor in the file to reset che code! 这样,我只需要使用文本编辑器在文件中写入“ 0”(零)即可重置密码! And if the server reboots i don't lose the actual number like using other methods (ie: variables saved in cache) 而且,如果服务器重启,我不会像使用其他方法那样丢失实际数量(即:保存在缓存中的变量)

The error i met is: no such file/directory called product_code.txt 我遇到的错误是:没有这样的文件/目录称为product_code.txt

Here the code of the model: 这里是模型的代码:

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"

The file product_code.txt is located in the same directory of models.py I ensure the error refer to the code line 文件product_code.txt位于models.py的同一目录中,我确保错误引用代码行

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

since i checked it with the debugger. 因为我用调试器检查过它。

Any idea to solve the problem? 有解决问题的主意吗? Thank you 谢谢

You should open the file in append mode: 您应该以append模式打开文件:

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

But I would consider using another method (maybe a database) unless you know from the start that you are not going to see any race condition. 但是我会考虑使用另一种方法(也许是数据库),除非您从一开始就知道不会看到任何竞争情况。

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

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