short_url.py

"""
Author:Kevin
Date:2022/07/31
Remark: 
"""
import json

from flask import Flask, render_template, request, redirect, jsonify
import re
import string
import random

app = Flask(__name__)
app.config['DEBUG'] = False


@app.route('/<code>/')
def target(code):
    with open('data.json', 'r', encoding='utf-8') as f:
        data = json.loads(f.read())
    url = data.get(code)
    if url:
        return redirect(url)
    return '访问的链接不存在'


@app.route('/', methods=['GET', 'POST'])
def url():
    if request.method == 'POST':
        target_url = request.form.get('url')
        msg = {'code': 200}
        if re.match(r'^https?:/{2}\w.+$', target_url):
            chars = string.ascii_uppercase + string.digits
            code = ''.join(random.sample(chars, 4))
            with open('data.json', 'r', encoding='utf-8') as f:
                data = json.loads(f.read(), )
            while code in data:
                code = ''.join(random.sample(chars, 4))

            msg['url'] = f'http://127.0.0.1:5000/{code}/'
            data[code] = target_url
            with open('data.json', 'w', encoding='utf-8') as f:
                f.write(json.dumps(data, indent=4))
            return jsonify(msg)
        else:
            msg['code'] = 201
            msg['msg'] = '输入网址不合法'
            return jsonify(msg)
    else:
        ip = request.remote_addr
        return render_template('short_url.html', ip=ip)


if __name__ == '__main__':
    app.run()

short_url.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
</head>
<body>
<div class="row">
    <div class="col-md-3 col-md-offset-4">
        <h1 class="text-center">短url生成</h1>
        <form action="" style="margin-bottom: 100px">
            <div class="form-group">
                <input type="text" class="form-control url" width="100px">
            </div>
            <input type="button" class="btn btn-primary btn-block" id="generate" value="生成">
            <h3>当前访问者IP: {{ ip }}</h3>
            <h4 class="text-center">

                <a class="short_url" href="" target="_blank"></a>
                <span style="color: red" class="error"></span>
            </h4>
        </form>
    </div>
</div>
</body>
<script>
    $('#generate').click(() => {
        let target_url = $('.url').val()
        $.ajax({
            url: "/",
            data: {
                'url': target_url
            },
            type: "POST",
            success: data => {
                if (data.code === 200) {
                    $('.error').text('')
                    $('.short_url').text(data.url).attr('href', data.url)
                } else {
                    $('.short_url').text('')
                    $('.error').text(data.msg)
                }


            }

        })
    })
</script>
</html>

data.json

{}

测试地址:http://101.43.194.220:5000

Last modification:August 1, 2022
如果觉得我的文章对你有用,请随意赞赏