-
Python Flask - URL 단축 및 QR 생성기Python 2024. 8. 2. 14:19반응형
1. 모듈 설치
pip install flask pyshorteners qrcode[pil]
2. app.py 생성
from flask import Flask, render_template, request, redirect, url_for import pyshorteners import qrcode import io from base64 import b64encode # pip install flask pyshorteners qrcode[pil] app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': url = request.form['url'] # URL 단축 s = pyshorteners.Shortener() short_url = s.tinyurl.short(url) # QR 코드 생성 qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(short_url) qr.make(fit=True) img = qr.make_image(fill='black', back_color='white') # 이미지 데이터를 바이트로 변환 buffer = io.BytesIO() img.save(buffer, format="PNG") img_str = b64encode(buffer.getvalue()).decode('utf-8') return render_template('index.html', short_url=short_url, qr_code=img_str) return render_template('index.html', short_url=None, qr_code=None) if __name__ == '__main__': app.run(debug=True)
3. templates/index.html 생성
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>URL 단축 및 QR 생성기</title> <style> body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; font-family: Arial, sans-serif; background-color: #f5f5f5; } .container { text-align: center; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } h1 { margin-bottom: 20px; } form { margin-bottom: 20px; } input[type="text"] { width: 80%; padding: 10px; margin: 10px 0; border: 1px solid #ccc; border-radius: 5px; } button { padding: 10px 20px; border: none; border-radius: 5px; background-color: #007bff; color: white; cursor: pointer; } button:hover { background-color: #0056b3; } .result { margin-top: 20px; } .result a { color: #007bff; text-decoration: none; } .result a:hover { text-decoration: underline; } </style> </head> <body> <div class="container"> <h1>URL 단축 및 QR 생성기</h1> <form method="post"> <label for="url">URL 정보 :</label> <input type="text" id="url" name="url" required> <button type="submit">입력</button> </form> {% if short_url %} <div class="result"> <h2>단축 URL : </h2> <p><a href="{{ short_url }}" target="_blank">{{ short_url }}</a></p> <h2>QR : </h2> <img src="data:image/png;base64,{{ qr_code }}" alt="QR Code"> </div> {% endif %} </div> </body> </html>
4. python app.py 로 flask 실행
127.0.0.1:5000 으로 웹 페이지 오픈
5. url 주소 입력 후 결과 확인
반응형'Python' 카테고리의 다른 글
Python을 이용한 엑셀 일괄 암호화 처리 (0) 2024.05.07 Python - Plivo를 이용한 SMS 보내기 (2) 2021.07.15 Python - Selenium Sample (0) 2021.05.03 DevTools listening on ws://127.0.0.1:12740/devtools/browser/... 오류 (0) 2021.03.13 Windows - vscode에서 가상환경 activate 안될 때 대처 (3) 2020.11.29 댓글