이미지 URL을 사용하여 각 이미지 인스턴스를 base64로 변환하려고합니다. 모든 이미지는 내 amazon-s3 버킷에 저장됩니다. 안타깝게도 생성 된 암호화가 recipe_plain.html 템플릿에 이미지를 표시하지 않습니다. 도움을 주시면 감사하겠습니다.
views.py
...
import base64
class RecipePlainView(DetailView):
model = Recipe
template_name = 'recipes/recipe_plain.html'
def get_context_data(self, **kwargs):
context = super(RecipePlainView, self).get_context_data(**kwargs)
image = self.object.image
image.open(mode='rb')
context['recipe_image_base64'] = base64.b64encode(image.read())
image.close()
return context
recipe_plain.html
<img src="data:image;base64,{{ recipe_image_base64 }}" alt="{{ recipe.image.name }}">
문제는 context [ 'recipe_image_base64'] 변수가 base64를 바이트 개체로 반환한다는 것입니다. 이것은 decode () 함수를 사용하여 해결되었습니다.
또한 요청 라이브러리를 사용하여 스크립트를 단순화하고 유효성 검사를 포함했습니다.
import base64, requests
class RecipePlainView(DetailView):
model = Recipe
template_name = 'recipes/recipe_plain.html'
def get_context_data(self, **kwargs):
url = self.object.image.url
r = requests.get(url)
if r.status_code == 200:
byteBase64 = base64.b64encode(requests.get(url).content)
context['recipe_image_base64'] = byteBase64.decode("utf-8")
else:
context['recipe_image_base64'] = False
return context
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다