#!/bin/sh
set -o errexit
set -o pipefail
set -o nounset
if [ $DJANGO_DEBUG == "on" ]; then
./manage.py runserver 0.0.0.0:8000
elif [ $DJANGO_MODE == "worker" ]; then
./manage.py runworker
else
daphne -b 0.0.0.0 -p 8000 config.asgi:application
fi
#!/usr/bin/env python3
import ast
filename = 'file.txt'
# open file
with open(filename) as f:
# read lines one by one
for line in f:
# remove semicolon and new line characters from the end of the line
line = line.rstrip('\n;')
# parse string
data = ast.literal_eval(line)
# print representation of the data
print(repr(data))
@BotFather
нужно создать нового бота, записать полученный token - <bot_token>
/login
с помощью /setcommands
uuidgen -r
) - <webhook_token>
http "https://api.telegram.org/bot<bot_token>/setWebhook?url=https://<domain_name>/bot/<webhook_token>/"
./manage.py createcachetable
settings.py
...
TELEGRAM_BOT_ACCESS_TOKEN = <bot_token>
TELEGRAM_BOT_WEBHOOK_TOKEN = <webhook_token>
TELEGRAM_BOT_OTP_TIMEOUT = 120
USE_X_FORWARDED_HOST = True
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'django_cache',
}
}
...
urls.py
...
from .views import BotView, LoginView
urlpatterns = [
...
path('bot/<uuid:token>/', BotView.as_view()),
path('login/<uuid:otp>/', LoginView.as_view(), name='login'),
]
views.py
import json
import requests
import uuid
from django.conf import settings
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
...
@method_decorator(csrf_exempt, name='dispatch')
class BotView(View):
def post(self, request, token):
if str(token) != settings.TELEGRAM_BOT_WEBHOOK_TOKEN:
return HttpResponseNotFound()
params = json.loads(request.body)
message = params['message']
if message.get('text') == '/login':
user = message['from']
chat_id = user['id']
data = {
'username': user['username'],
'first_name': user.get('first_name', ''),
'last_name': user.get('last_name', ''),
}
otp = uuid.uuid4()
cache.set(otp, data, settings.TELEGRAM_BOT_OTP_TIMEOUT)
path = reverse('login', args=[otp])
login_url = request.build_absolute_uri(path)
url = 'https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}'.format(
settings.TELEGRAM_BOT_ACCESS_TOKEN,
chat_id,
login_url,
)
requests.get(url, timeout=10)
return HttpResponse('')
class LoginView(TemplateView):
template_name = 'login.html'
def dispatch(self, request, otp):
self.data = cache.get(otp, {})
return super().dispatch(request, otp)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['data'] = self.data
return context
def post(self, request, otp):
cache.delete(otp)
username = self.data.get('username')
if not username:
return HttpResponseRedirect(request.path)
user, created = User.objects.update_or_create(
username=username,
defaults={
'first_name': self.data.get('first_name', ''),
'last_name': self.data.get('last_name', ''),
},
)
login(request, user)
path = reverse('home')
return HttpResponseRedirect(path)
templates/login.html
{% extends 'bootstrap4/bootstrap4.html' %}
{% block bootstrap4_content %}
<div class="container">
<div style="padding:5rem; text-align:center;">
{% if not data %}
<h1>This url invalid or expired.</h1>
{% else %}
<h1>Login as {{ data.username }}</h1>
<form action="" method="post">
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg btn-block">
Login
</button>
</form>
{% endif %}
</div>
</div>
{% endblock %}
import os
from django.db import models
class Article(models.Model):
title = models.CharField(
max_length=200,
)
image = models.ImageField(
blank=True,
upload_to='images',
)
@property
def thumbnail(self):
if self.image:
path, filename = os.path.split(self.image.url)
name, ext = os.path.splitext(filename)
filename = 'prefix_' + name + '_suffix' + ext
return os.path.join(path, filename)
import os
from django.contrib import admin
from django.utils.html import format_html
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = (
'title',
'get_thumbnail',
)
fields = (
'title',
'get_thumbnail',
)
readonly_fields = (
'get_thumbnail',
)
def get_thumbnail(self, obj):
if obj.image:
path, filename = os.path.split(self.image.url)
name, ext = os.path.splitext(filename)
filename = 'prefix_' + name + '_suffix' + ext
return format_html('<img src="{}">', os.path.join(path, filename))
get_thumbnail.short_description = 'Thumbnail'
get_logo.admin_order_field = 'image'
import os
from django.contrib import admin
from django.utils.html import format_html
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = (
'title',
'get_thumbnail',
)
fields = (
'title',
'get_thumbnail',
)
readonly_fields = (
'get_thumbnail',
)
def get_thumbnail(self, obj):
url = obj.thumbnail
return format_html('<img src="{}">', url) if url else ''
get_thumbnail.short_description = 'Thumbnail'
get_logo.admin_order_field = 'image'
pg_dump -Fc db_name | ssh user@new_server "pg_restore -d db_name"
import itertools
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
...
limit = 250
for index, items in enumerate(grouper(rows, limit)):
items = (i for i in items if i) # remove empty rows added by grouper
products = []
for item in items:
product = Product(
price=item[0],
shipping=item[1],
)
products.append(product)
Product.objects.bulk_create(products)
from django.db import transaction
...
limit = 250
for index, items in enumerate(grouper(rows, limit)):
with transaction.atomic():
for item in (i for i in items if i):
product = Product.objects.create(
price=item[0],
shipping=item[1],
)
# product can be used there to create another objects, e.g.:
for color in item[2].split(','):
ProductColor.objects.create(
product=product,
color=color,
)
import hashlib
import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.db import models
def upload_to(instance, filename, fieldname):
ext = os.path.splitext(filename)[1].lower()
class_name = instance.__class__.__name__.lower()
h = hashlib.sha256()
field = getattr(instance, fieldname)
for chunk in field.chunks():
h.update(chunk)
name = h.hexdigest()
return os.path.join(
class_name,
name + ext,
)
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name, max_length=None):
if self.exists(name):
os.remove(os.path.join(settings.MEDIA_ROOT, name))
return name
class Article(models.Model):
image = models.ImageField(
storage=OverwriteStorage(),
upload_to=lambda inst, fn: upload_to(inst, fn, 'image'),
)
pip install django-hashedfilenamestorage
DEFAULT_FILE_STORAGE = 'django_hashedfilenamestorage.storage.HashedFilenameFileSystemStorage'