python django网址生成二维码小应用


url.py

urlpatterns = [
    path('', views.index, name='index'),
]


view.py

from django.utils.six import BytesIO
import qrcode
from django.http import HttpResponse
from django.shortcuts import render



def index(request):
    if request.method == "GET":
        return render(request, 'index.html')
    else:
        website = request.POST.get('website')
        if (len(website) != 0):
            img = qrcode.make(str(website))
            buf = BytesIO()
            img.save(buf)
            image_stream = buf.getvalue()
            response = HttpResponse(image_stream, content_type="image/png")
            return response
        return HttpResponse(u"网址不能为空!")


index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>django网址转二维码小应用</title>
</head>
<body>
    <form method='post' action=''>
        <p>网址:<input type='text' name='website' value=''></p>
        <button type="submit">提交</button>
        {% csrf_token %}
    </form>
</body>
</html>

实例图:

二维码_20201211195625_683.jpg