1. 程式人生 > >Python 的request模組上傳圖片到django,資料庫儲存路徑名,後臺框架django DRF

Python 的request模組上傳圖片到django,資料庫儲存路徑名,後臺框架django DRF

請求方式為post方式:

上傳圖片部分

import requests

def main():
    with open('../2222.jpg','rb') as f:
        img = f.read()
    file = {'image':('img.jpg',img,'image/jpg')}    # image為欄位名  不能修改

    connt = requests.post('http://192.168.1.180:8000/kolinfo/',files=file)
    print(connt.content.decode('utf-8'))


if __name__ == '__main__':
    main()

如下   django 模型類中帶有圖片欄位,上傳圖片的程式碼如上 

def user_directory_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '{}.{}'.format(uuid.uuid4().hex[:8], ext)
    # return the whole path to the file
    return "{0}/{1}/{2}".format("image", datetime.datetime.now().strftime('%Y/%m/%d'),filename)


class 模型類名(models.Model):

    image = models.ImageField(default='',null=True,blank=True,verbose_name='頭像',upload_to=user_directory_path)



    class Meta:
        db_table = '表名'

檢視自行定義