• Nie jesteś zalogowany.

#1 Gru 17, 2014 16:53:49

keNzi
Zarejestrowany: 2009-11-06
Wiadomości: 547
Reputacja: +  7  -
Profil   Wyślij e-mail  

[PYTHON] Skracanie linków w Bitly.com

Jako, że to nowy dział to pozwolę sobie zacząć od pochwalenia się co stworzyłem na potrzeby naszej redakcji.

Jest to kod napisany w technologii Python / Django, dzięki któremu możemy tworzyć skrócone linki z naszego panelu.

Zatem przejdźmy do kodu

views.py

# -*- coding: utf-8 -*-
from django.views.generic import ListView, DetailView, CreateView
from braces.views import LoginRequiredMixin
from .forms import BitlyForm
from .models import Bitly
class BitlyIndexListView(LoginRequiredMixin, ListView):
    """
    Bitly shorten urls listing page.
    URL: {% url bitly:index %}
    """
    model = Bitly
    template_name = 'bitly/bitly_index.html'
class BitlyDetailView(LoginRequiredMixin, DetailView):
    """
    Bitly shorten url detail view.
    URL: {% url bitly:detail %}
    """
    model = Bitly
    template_name = 'bitly/bitly_detail.html'
class BitlyCreateView(LoginRequiredMixin, CreateView):
    """
    Bitly shorten url create view.
    URL: {% url bitly:create %}
    """
    model = Bitly
    form_class = BitlyForm
    def get_context_data(self, **kwargs):
        context = super(BitlyCreateView, self).get_context_data(**kwargs)
        context['user'] = self.request.user
        return context

urls.py
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from .views import BitlyIndexListView
from .views import BitlyDetailView
from .views import BitlyCreateView
urlpatterns = patterns('',
                       # {% url bitly:index %}
                       url(r'^$',
                           BitlyIndexListView.as_view(),
                           name='index'),
                       # {% url bitly:detail %}
                       url(r'^(?P<pk>\d+)/$',
                           BitlyDetailView.as_view(),
                           name='detail'),
                       # {% url bitly:create %}
                       url(r'^create/$',
                           BitlyCreateView.as_view(),
                           name='create'),
                       )

models.py

# -*- coding: utf-8 -*-
import bitly_api
from django.db import models
from django.core.urlresolvers import reverse
BITLY_LOGIN = 'login'
BITLY_API_KEY = 'TWÓJ_API_KEY'
BITLY_ACCESS_TOKEN = 'TWOJ_ACCESS_TOKEN'
def get_bitly_shorten_url(long_url):
    """
    Function to get shorten_url from bit.ly through API
    """
    # use oauth2 endpoints
    c = bitly_api.Connection(access_token=BITLY_ACCESS_TOKEN)
    response = c.shorten(uri=long_url)
    return response['url']
class Bitly(models.Model):
    """
    Model that provides fields for Bit.ly shorten links.
    """
    name = models.CharField('Nazwa',
                            help_text='Nazwa rozpoznawcza dla danego linku.',
                            max_length=300,
                            blank=True)
    long_url = models.CharField('Długi URL',
                                help_text='Długi link do skrócenia.',
                                max_length=5000)   # For partners links. Yea ;/
    shorten_url = models.CharField('Krótki URL',
                                   help_text='Link po skróceniu.',
                                   max_length=50,
                                   blank=True)
    class Meta:
        verbose_name_plural = 'Bitly'
    def __unicode__(self):
        return self.long_url
    def save(self, *args, **kwargs):
        # Do it only if Bitly object has given a long_url
        if self.long_url:
            self.shorten_url = get_bitly_shorten_url(self.long_url)
        # Call the 'real' save()
        super(Bitly, self).save(*args, **kwargs)
    def get_absolute_url(self):
        return reverse('bitly:detail', kwargs={'pk': self.id})

forms.py

# coding: utf-8
from django import forms
from .models import Bitly
class BitlyForm(forms.ModelForm):
    """
    Form for Bitly shorten url model.
    """
    class Meta:
        model = Bitly

oraz template do wyświetlenia template'ów

bitly/bitly_index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Panel zarządzania linkami Bit.ly</title>
</head>
<body>
{% for object in object_list %}
    Name: <a href="{% url bitly:detail object.id %}">{{ object.name }}</a><br />
    Long: {{ object.long_url }}<br />
    Short: {{ object.shorten_url }}<br />
    ID: {{ object.id }}<br />
{% endfor %}
</body>
</html>

bitly/bitly_detail.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Panel zarządzania linkami Bit.ly</title>
</head>
<body>
{{ object.name }}<br />
{{ object.long_url }}<br />
{{ object.shorten_url }}<br /><br />
<p><a href="/bitly/create/">Dodaj kolejny</a></p>
</body>

bitly/bitly_form.html

<form action="{% url bitly:create %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save">
</form>



Top Dog & Growth Hacker & Django/Python Developer

Edytowany keNzi (Gru 17, 2014 16:55:09)

Offline

Stopka forum

Narzędzia moderatora

Lo-Fi Version