django simple to achieve short url

First, the principle of short url

What is short url:

Simply, it is the URL ordinary normal visit, conversion into a short URL, for example: https: //www.cnblogs.com/angelyan/articles/10667354.html#_label0 turn into https://dwz.cn/p8VGVkMt

Role advantages: short, less character, beautiful, easy to publish, transmit, breaking some platform restrictions

Principle steps:

1. The browser parses DNS, obtain the corresponding domain name ip

2. Get IP, http request sent, acquired p8VGVkMt corresponding long link address

3.http 301 redirects, go to the corresponding linked pages long

Algorithm works:

Id database using increment, each time acquiring a short url database id, the id 62 for binary conversion, to obtain a short code, so that up to eight short codes, the shortest one.

Second, the code portion

#url路由部分

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index),
    url(r'^addShortUrl/$', views.addShortUrl),
    url(r'^restoreUrl/$', views.restoreUrl),
    url(r'^([A-Za-z0-9]+)/', views.url),

]
#模型表部分
from django.db import models

# Create your models here.

# 短url表
class ShortUrl(models.Model):
    id=models.AutoField(primary_key=True)
    # 短url
    short_url=models.CharField(max_length=255)
    # 原始url
    ori_url = models.TextField()
    # 短url有效期
    period=models.DateTimeField()

    def __str__(self):
        return self.short_url
# View part view 

from django.shortcuts Import the render, the redirect
 from django.utils.httpwrappers Import the HttpResponse, jsonResponse 

# the Create your views here Wallpaper. 
Import Re, datetime, Time
 from app01 Import Models 

baseList = ' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' 
# 10 hex 62 hex transfected 
def ChangeBase (n-, B):
     # returns the quotient and the remainder comprising a tuple (n-// B, n-% B) 
    X, Y = divmod (n-, B)
     Print (X, Y)
     IF X> 0:
        return ChangeBase (X, B) + baseList [Y]
     the else :
         return baseList [Y]
 # utilizing self-energizing id generator n mysql database, and then converted into 62 hex, 62 hex and then stored into the addressed long url mysql, query 62 hexadecimal next visit short url corresponding long url, 
# last 301 redirect to the long url 

DEF index (Request):
     IF request.method == " GET " :
         return the render (Request, " index.html " ) 

DEF url (Request, url):
     IF request.method == " GET " : 
        RES = models.ShortUrl.objects.filter (short_url = url) .first ()
        if not res or not res.ori_url:
            return HttpResponse("没有此短网址")
        if time.time()-int(time.mktime(res.period.timetuple()))>0:
            return HttpResponse("短网址已失效")
        return redirect(res.ori_url)
    if request.method=="POST":
        return HttpResponse("Request error")

def addShortUrl(request):
    if request.is_ajax():
        response = {"status": 100, "msg": None}
        long = request.POST.get('long')
        period = request.POST.get('period')
        print(long,period)
        res=re.search("^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)?"
                      "((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\."
                      "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\."
                      "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\."
                      "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|"
                      "([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.[a-zA-Z]{2,4})(\:[0-9]+)?"
                      "(/[^/][a-zA-Z0-9\.\,\?\'\\/\+&%\$#\=~_\-@]*)*$",long)
        if not res:
            response["msg"]="网址错误"
            response["status"]=101
        elif period !="一年期" long-term"period! =and" : 
            Response [ " MSG " ] = " valid format error " 
            Response [ " Status " ] = 102
         the else : 
            DATE = datetime.datetime.now ()
             IF period == " year " : 
                DATE = datetime.datetime.now () + datetime.timedelta (Days = 365 )
             IF period == " long-term " : 
                DATE = datetime.datetime.now () + datetime.timedelta (Days = 365 * 5 )
            res = models.ShortUrl.objects.create(period=date)
            print(res.id)
            n=res.id
            short_url=changeBase(n,62)
            if short_url=="admin" or short_url=="addShortUrl" or short_url=="restoreUrl":
                response["msg"] = "请求再转换一次试试"
                response["status"] = 103
            else:
                models.ShortUrl.objects.filter(id=n).update(short_url=short_url,ori_url=long)
                response["msg"] = short_url

        return JsonResponse(response)
    if request.method == "GET":
        return HttpResponse("No get method")

def restoreUrl(request):
    if request.is_ajax():
        response = {"status": 100, "msg": None}
        short = request.POST.get('short')
        res = re.search("^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)?"
                        "((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\."
                        "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\."
                        "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\."
                        "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|"
                        "([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.[a-zA-Z]{2,4})(\:[0-9]+)?"
                        "(/[^/][a-zA-Z0-9\.\,\?\'\\/\+&%\$#\=~_\-@]*)*$", short)
        if not res or "/" not in short:
            response["msg"] = "网址错误"
            response["status"] = 101

        else:
            short_url=short.split("/")[-1]
            res=models.ShortUrl.objects.filter(short_url=short_url).first()
            print(res)
            if not res:
                response["msg"] = "没有该短网址"
                response["status"] = 102
            else:
                response["msg"] = res.ori_url

        return JsonResponse(response)
#模板部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <title>短url</title>
</head>
<body>

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <form action="" method="post" id="form">
            {% csrf_token %}
            <h1 style="text-align: center">短url</h1>
            <hr>

            <div class="span12">
                <div class="tabbable" id="tabs-149852">
                    <ul class="nav nav-tabs">
                        <li class="active">
                            <a href="#panel-24341" data-toggle="tab">缩短网址</a>
                        </li>
                        <li>
                            <a href="#panel-186783" data-toggle="tab">还原网址</a>
                        </li>
                    </ul>
                    <div class="tab-content">
                        <div class="tab-pane active" id="panel-24341">
                            <br>
                            <div class="form-group">
                                <label for="long" class="sr-only">缩短网址</label>
                                <input type="text" class="form-control" id="long"
                                       placeholder="缩短网址">
                                <br>
                                <button type="button" class="btn btn-primary" id="but_add">缩短网址</button>
                            </div>


                            <div class="form-inline">
                                <p class="form-control-static">有效期:</p>
                                <select class="form-control" id="period">
                                    <option value="一年期">一年期</option>
                                    <option value="长期">长期</option>
                                </select>
                            </div>
                        </div>
                        <div class="tab-pane" id="panel-186783">
                            <br>
                            <form class="form-inline">
                                <label for="short" class="sr-only">还原网址</label>
                                <input type="text" class="form-control" id="short"
                                       placeholder="还原网址">
                                <br>
                                <button type="button" class="btn btn-primary" id="but_restore">Button</Reduction URLs>

                            </form>
                        </div>
                    </div>
                </div>
            </div>

        </form>
    </div>
</div>
</body>
<script src="/static/js/jquery-3.3.1.js"></script>
<script src="/static/bootstrap-3.3.7-dist/js/bootstrap.js"></script>

<script>
    $("#but_add").click(function () {

        var formdata={"long":$("#long").val(),"period":$("#period").val(),"csrfmiddlewaretoken":"{{ csrf_token }}"}
        console.log(formdata);

        $.ajax({
            url: "/addShortUrl/",
            type: "post",
            data: formdata,
            success: function (data) {
                if (data.status == 100) {
                    var  a = document.createElement('a');
                    a.href = location.href+data.msg;
                    alert(a)
                } else {
                    alert(data.msg);
                }
            }

        })
    });
    $("#but_restore").click(function () {

        var formdata={"short":$("#short").val(),"csrfmiddlewaretoken":"{{ csrf_token }}"};
        console.log(formdata);

        $.ajax({
            url: "/restoreUrl/",
            type: "post",
            data: formdata,
            success: function (data) {
                if (data.status == 100) {
                    alert(data.msg);
                } else {
                    alert(data.msg);
                }
            }

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

 

 

 

Guess you like

Origin www.cnblogs.com/angelyan/p/11830802.html