app.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from flask import Flask, render_template, request, redirect
  2. import pymysql
  3. import random
  4. import string
  5. from flask_bootstrap import Bootstrap
  6. app = Flask(__name__)
  7. Bootstrap(app)
  8. # 配置 MySQL 数据库连接
  9. app.config['MYSQL_DATABASE_USER'] = 'root'
  10. app.config['MYSQL_DATABASE_PASSWORD'] = 'guo784512'
  11. app.config['MYSQL_DATABASE_DB'] = 'your_database'
  12. app.config['MYSQL_DATABASE_HOST'] = 'localhost'
  13. app.config['MYSQL_DATABASE_PORT'] = 3306
  14. # 初始化 MySQL 连接
  15. db = pymysql.connect(
  16. user=app.config['MYSQL_DATABASE_USER'],
  17. password=app.config['MYSQL_DATABASE_PASSWORD'],
  18. database=app.config['MYSQL_DATABASE_DB'],
  19. host=app.config['MYSQL_DATABASE_HOST'],
  20. port=app.config['MYSQL_DATABASE_PORT']
  21. )
  22. def is_short_url_exists(short_url):
  23. with db.cursor() as cursor:
  24. cursor.execute("SELECT COUNT(*) FROM urls WHERE short_url = %s", (short_url,))
  25. result = cursor.fetchone()
  26. return result[0] > 0
  27. def generate_unique_short_url():
  28. current_length = 3
  29. while True:
  30. short_url = ''.join(random.choices(string.digits + string.ascii_letters, k=current_length))
  31. if not is_short_url_exists(short_url):
  32. yield short_url # 使用 yield 生成迭代器
  33. current_length = 4 # 在使用完当前长度后,设置下一次长度为4
  34. short_url_generator = generate_unique_short_url()
  35. @app.route('/')
  36. def index():
  37. return render_template('index.html')
  38. @app.route('/shorten', methods=['POST'])
  39. def shorten():
  40. original_url = request.form['url']
  41. # 检查原始链接是否已经有对应的短链接
  42. with db.cursor() as cursor:
  43. cursor.execute("SELECT short_url FROM urls WHERE original_url = %s", (original_url,))
  44. result = cursor.fetchone()
  45. if result:
  46. existing_short_url = result[0]
  47. return render_template('result.html', original_url=original_url, short_url=existing_short_url)
  48. # 如果没有,生成新的短链接
  49. short_url = next(short_url_generator)
  50. # 将原始URL和短网址保存到数据库
  51. with db.cursor() as cursor:
  52. cursor.execute("INSERT INTO urls (original_url, short_url) VALUES (%s, %s)", (original_url, short_url))
  53. db.commit()
  54. return render_template('result.html', original_url=original_url, short_url=short_url)
  55. @app.route('/<short_url>')
  56. def redirect_to_original(short_url):
  57. # 从数据库中获取原始URL并重定向
  58. with db.cursor() as cursor:
  59. cursor.execute("SELECT original_url FROM urls WHERE short_url = %s", (short_url,))
  60. result = cursor.fetchone()
  61. if result:
  62. original_url = result[0]
  63. return redirect(original_url)
  64. else:
  65. return "Short URL not found."
  66. if __name__ == '__main__':
  67. # 创建数据库表
  68. with app.app_context():
  69. with db.cursor() as cursor:
  70. cursor.execute("CREATE TABLE IF NOT EXISTS urls (id INT AUTO_INCREMENT PRIMARY KEY, original_url VARCHAR(255), short_url VARCHAR(255), UNIQUE KEY short_url_unique (short_url))")
  71. db.commit()
  72. app.run(debug=True, port=8082) # 将端口号改为 8082