美文网首页
短网址系统设计

短网址系统设计

作者: 木叶苍蓝 | 来源:发表于2023-03-14 16:43 被阅读0次
    微信截图_20230315162548.png
    def mybin(num):
        if num == 0: return 0
    
        res = []
        while num:
            num, rem = divmod(num, 2)
            res.append(str(rem))
        return ''.join(reversed(res))
    
    CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
    def encode(num):
        if num == 0: return CHARS[0]
    
        res = []
        while num:
            num, rem = divmod(num, len(CHARS))
            res.append(CHARS[rem])
        return ''.join(reversed(res))
    
    schema.sql
    CREATE TABLE short_url (
        id bigint unsigned NOT NULL AUTO_INCREMENT,
        token varchar(10),
        url varchar(2048),
        created_at timestemp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY(`id`),
        KEY `idx_token` (`token`)
    );
    
    
    short_url_app.py
    import os
    
    from flask import Flask, jsonify, render_template, request
    from flask_mysqldb import MySQL
    from flask.ext.redis import FlaskRedis
    
    app = Flask(__name__)
    app.config["MYSQL_USER"] = 'root'
    app.config["MYSQL_PASSWORD"] = os.getenv('MYSQL_PASS')
    app.config['MYSQL_DB'] = 'test'
    app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
    
    mysql = MySQL(app)
    redis_store = FlaskRedis(app)
    
    CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
    
    def encode(num):
        if num == 0: return CHARS[0]
    
        res = []
        while num:
            num, rem = divmod(num, len(CHARS))
            res.append(CHARS[rem])
        return ''.join(reversed(res))
    
    
    @app.route('/shorten', methods=['POST'])
    def shorten_url():
        long_url = request.json['url']
        index = int(redis_store.incr('SHORT_CNT'))
        token = encode(index)
        sql = "INSERT INTO short_url(token, url) VALUES (%s, %s)"
        cur = mysql.connection.cursor()
        cur.execute(sql, (token, long_url))
        mysql.connection.commit()
        short_url = 'https://short.com/' + token
        return jsonify(url=short_url)
    
    
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    if __name__ == '__main__':
        app.run(debug=1)
    
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:短网址系统设计

          本文链接:https://www.haomeiwen.com/subject/xukkrdtx.html