引子:一個圖片上傳功能,用騰訊雲cos,一直找不到錯誤原因,結果是.env檔案中的行內註釋!
錯誤描述
- 上傳圖片程式碼
def action_upload_img_cloud(request):
user = CustomUser.objects.get(id=request.user_id)
file = request.FILES['img']
file_name = file.name
unique_file_name = f"{uuid.uuid4().hex}_{file_name}"
try:
config = CosConfig(Region=settings.TENCENT_CLOUD_REGION, SecretId=settings.TENCENT_CLOUD_SECRET_ID, SecretKey=settings.TENCENT_CLOUD_SECRET_KEY)
client = CosS3Client(config)
response = client.put_object(Bucket=settings.TENCENT_CLOUD_BUCKET, Body=file, Key=unique_file_name)
response_url = f'https://{settings.TENCENT_CLOUD_BUCKET}.cos.{settings.TENCENT_CLOUD_REGION}.myqcloud.com/{unique_file_name}'
except Exception as e:
print(e)
return err(404, '騰訊雲配置錯誤')
Image新增資料庫記錄
image = Image.objects.create(
image=response_url,
uploader=user
)
return result({'url': response_url})
一直報錯:region format is illegal, only digit, letter and - is allowed!
解決
- 跟蹤到報錯位置,是
TENCENT_CLOUD_REGION
的問題
settings的變數來自.env檔案,
.env配置
# @ 騰訊雲cos配置
TENCENT_CLOUD_SECRET_ID = '=================='
TENCENT_CLOUD_SECRET_KEY = '=================='
TENCENT_CLOUD_BUCKET = 'wutnote-13424424'
TENCENT_CLOUD_REGION = 'ap-shanghai' # 儲存桶所在區域
沒錯,就是行內註釋!!搗的鬼
去除# 儲存桶所在區域
行內註釋終於通了。