引子:一个图片上传功能,用腾讯云cos,一直找不到错误原因,结果是.env文件中的行内注释!
错误描述
- 上传图片代码
def action_upload_img_cloud(request):user = CustomUser.objects.get(id=request.user_id)file = request.FILES['img']file_name = file.nameunique_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' # 存储桶所在区域
没错,就是行内注释!!捣的鬼
去除# 存储桶所在区域
行内注释终于通了。