簡體   English   中英

讀寫文本文件

[英]reading and writing text file

我正在編寫一個項目,目標是使用Django構建類似管理(業務管理,怎么說)的內容。

實際上,我需要一個全局變量的支持,因為產品是由不斷增加的代碼標識的,有時我會對其進行重置( 這不是主鍵,只是我用來工作的代碼 )。 因此,為避免使用全局變量,同樣由於問題,如果服務器重新啟動,我會感到煩惱,我想在文本文件上寫入實際代碼。

使用覆蓋的保存方法時,我將數字保留在此文件中,並用它來填寫產品代碼字段。 然后,我增加寫入文件的數量並關閉它。 這樣,我只需要使用文本編輯器在文件中寫入“ 0”(零)即可重置密碼! 而且,如果服務器重啟,我不會像使用其他方法那樣丟失實際數量(即:保存在緩存中的變量)

我遇到的錯誤是:沒有這樣的文件/目錄稱為product_code.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+')

因為我用調試器檢查過它。

有解決問題的主意嗎? 謝謝

您應該以append模式打開文件:

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

但是我會考慮使用另一種方法(也許是數據庫),除非您從一開始就知道不會看到任何競爭情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM