for index, item in enumerate(['вася', 'петя', 'саша'], start=1):
print(f'{item}\nСтрока № {index}')
import ipaddress
mac_addresses = ['aa:bb:cc:aa:bb:11', 'aa:bb:cc:aa:bb:12', 'aa:bb:cc:aa:bb:13', 'aa:bb:cc:aa:bb:14', 'aa:bb:cc:aa:bb:15']
start_ip = ipaddress.ip_address('192.168.0.11')
for index, mac_address in enumerate(mac_addresses):
print(f'MAC {mac_address}\nIP {start_ip + index}\n')
MAC aa:bb:cc:aa:bb:11
IP 192.168.0.11
MAC aa:bb:cc:aa:bb:12
IP 192.168.0.12
MAC aa:bb:cc:aa:bb:13
IP 192.168.0.13
MAC aa:bb:cc:aa:bb:14
IP 192.168.0.14
MAC aa:bb:cc:aa:bb:15
IP 192.168.0.15
from django.db import models
from django.utils.translation import ugettext_lazy as _
class SchoolClass(models.Model):
name = models.CharField(
_('Класс'),
max_length=10,
db_index=True,
unique=True,
help_text=_('Название класса.'),
)
class Meta:
verbose_name = _('Класс')
verbose_name_plural = _('Классы')
def __str__(self):
return self.name
class Pupil(models.Model):
first_name = models.CharField(
_('Имя'),
max_length=100,
db_index=True,
help_text=_('Имя учащегося.'),
)
last_name = models.CharField(
_('Фамилия'),
max_length=100,
db_index=True,
help_text=_('Фамилия учащегося.'),
)
school_class = models.ForeignKey(
to=SchoolClass, on_delete=models.CASCADE,
verbose_name=_('Класс'), related_name='pupils',
help_text=_('Название класса.'),
)
class Meta:
verbose_name = _('Ученик')
verbose_name_plural = _('Ученики')
indexes = (
models.Index(fields=['first_name', 'last_name']),
)
def __str__(self):
return self.full_name
@property
def full_name(self):
return '{} {}'.format(self.first_name, self.last_name)
class Schedule(models.Model):
ATTEND = 'attend'
ABSENT = 'absent'
STATUS_CHOICES = (
(ATTEND, 'Присутствовал'),
(ABSENT, 'Отсутствовал'),
)
pupil = models.ForeignKey(
to=Pupil, on_delete=models.CASCADE,
verbose_name=_('Ученик'), related_name='schedules',
help_text=_('Фамилия и имя учащегося.')
)
date = models.DateField(
_('Дата'),
db_index=True,
help_text=_('Дата.')
)
status = models.CharField(
_('Статус'), max_length=10,
choices=STATUS_CHOICES, default=ABSENT,
db_index=True,
help_text=_('Статус.')
)
class Meta:
verbose_name = _('Расписание')
verbose_name_plural = _('Расписания')
indexes = (
models.Index(fields=['date', 'status']),
)
unique_together = ('pupil', 'date',)
from django.contrib import admin
from schedule.models import (
SchoolClass,
Pupil,
Schedule
)
class PupilInLIne(admin.TabularInline):
model = Pupil
fields = ('first_name', 'last_name')
extra = 1
class ScheduleInLIne(admin.TabularInline):
model = Schedule
fields = ('date', 'status')
extra = 1
@admin.register(SchoolClass)
class SchoolClassAdmin(admin.ModelAdmin):
list_display = ('name',)
list_display_links = ('name',)
inlines = (PupilInLIne,)
list_filter = ('name',)
search_fields = ('name',)
@admin.register(Pupil)
class PupilAdmin(admin.ModelAdmin):
list_display = ('full_name', 'school_class')
list_display_links = ('full_name',)
inlines = (ScheduleInLIne,)
raw_id_fields = ('school_class',)
list_select_related = ('school_class',)
search_fields = ('first_name', 'last_name', 'school_class__name')
list_filter = ('school_class__name',)
class PupilScheduleDetailView(DetailView):
model = Pupil
template_name = 'pupil_schedule_detail.html'
def get_context_data(self, **kwargs):
context_data = super().get_context_data(**kwargs)
schedule_queryset = self.object.schedules.all().select_related(
'pupil'
).values(
'pupil__first_name',
'pupil__last_name',
'date', 'status'
)
context_data.update({
'schedules': schedule_queryset
})
return context_data
{% if schedules %}
<table>
{% for schedule in schedules %}
<tr>
<td>{{ schedule.pupil__first_name }} {{ schedule.pupil__last_name }}</td>
<td>{{ schedule.date }}</td>
<td>{{ schedule.status }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>Данных нет!</p>
{% endif %}
Python 3.6.5 (default, Mar 29 2018, 03:28:50)
[GCC 5.4.0 20160609] on linux
aiohttp==3.2.1
import asyncio
import logging
import sys
import time
import aiohttp
logger = logging.getLogger('aiohttp_test')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
URL = 'https://api.github.com/events'
MAX_CLIENTS = 2
async def fetch_async(session, pid):
logger.info(f'Fetch async process {pid} started')
start = time.time()
async with session.get(URL) as response:
datetime = response.headers.get('Date')
logger.info(f'Process {pid}: {datetime}, took: {time.time() - start} seconds')
return datetime
async def asynchronous():
start = time.time()
async with aiohttp.ClientSession() as session:
tasks = [asyncio.ensure_future(
fetch_async(session, pid)) for pid in range(1, MAX_CLIENTS + 1)]
await asyncio.gather(*tasks)
logger.info(f'Process took: {time.time() - start} seconds')
if __name__ == '__main__':
io_loop = asyncio.get_event_loop()
try:
logger.info('Script has been started')
io_loop.run_until_complete(asynchronous())
except Exception as e:
logger.exception(e)
finally:
logger.info('Script has been finished')
io_loop.close()
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='base.html'), name="home"),
# Django Admin, use {% url 'admin:index' %}
url(settings.ADMIN_URL, include(admin.site.urls)),
url(r'^accounts/', include('allauth.urls')),
# Your stuff: custom urls includes go here
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework.reverse import reverse_lazy
from rest_framework.test import APIRequestFactory, APITestCase
from src.apps.book.factories import AuthorFactory, BookFactory
from src.apps.book.views import AuthorViewSet, BookViewSet
class BookSerializerTestCase(APITestCase):
def setUp(self):
super(BookSerializerTestCase, self).setUp()
self.authors = AuthorFactory.create_batch(size=2)
self.books = BookFactory.create_batch(size=2, author=self.authors[0])
self.factory = APIRequestFactory()
def tearDown(self):
super(BookSerializerTestCase, self).tearDown()
AuthorFactory.reset_sequence()
BookFactory.reset_sequence()
def test_author_list_view_set(self):
view = AuthorViewSet.as_view({'get': 'list'})
request = self.factory.get(reverse_lazy('author-list'))
response = view(request)
self.assertEqual(response.status_code, 200)
def test_author_retrieve_view_set(self):
view = AuthorViewSet.as_view({'get': 'retrieve'})
request = self.factory.get(reverse_lazy('author-detail', args=(self.authors[0].pk,)))
response = view(request, id=self.authors[0].pk)
self.assertEqual(response.status_code, 200)
def test_book_list_view_set(self):
view = BookViewSet.as_view({'get': 'list'})
request = self.factory.get(reverse_lazy('book-list'))
response = view(request)
self.assertEqual(response.status_code, 200)
def test_book_retrieve_view_set(self):
view = BookViewSet.as_view({'get': 'retrieve'})
request = self.factory.get(reverse_lazy('book-detail', args=(self.books[0].isbn,)))
response = view(request, isbn=self.books[0].isbn)
self.assertEqual(response.status_code, 200)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import serializers
from src.apps.book.models import AuthorModel, BookModel
class BookAuthorSerializer(serializers.ModelSerializer):
url = serializers.CharField(source='get_absolute_url', read_only=True)
name = serializers.CharField(source='get_name', read_only=True)
class Meta:
model = AuthorModel
exclude = ('id', 'first_name', 'last_name')
class BookSerializer(serializers.ModelSerializer):
url = serializers.CharField(source='get_absolute_url', read_only=True)
author = BookAuthorSerializer()
class Meta:
model = BookModel
fields = '__all__'
class AuthorBookSerializer(serializers.ModelSerializer):
url = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = BookModel
exclude = ('isbn', 'author')
class AuthorListSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='get_name', read_only=True)
url = serializers.CharField(source='get_absolute_url', read_only=True)
book_count = serializers.CharField(source='get_book_count', read_only=True)
class Meta:
model = AuthorModel
exclude = ('first_name', 'last_name')
class AuthorRetrieveSerializer(AuthorListSerializer):
books = AuthorBookSerializer(many=True, read_only=True)
class Meta:
model = AuthorModel
exclude = ('book_count', 'first_name', 'last_name')
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import viewsets
from rest_framework_extensions.mixins import DetailSerializerMixin
from src.apps.book.models import AuthorModel, BookModel
from src.apps.book.permissions import IsAccountAdminOrReadOnly
from src.apps.book.serializers import AuthorListSerializer, AuthorRetrieveSerializer, BookSerializer
class AuthorViewSet(DetailSerializerMixin, viewsets.ModelViewSet):
model = AuthorModel
queryset = AuthorModel.objects.prefetch_related('books').all()
serializer_class = AuthorListSerializer
serializer_detail_class = AuthorRetrieveSerializer
permission_classes = [
IsAccountAdminOrReadOnly
]
lookup_field = 'id'
class BookViewSet(viewsets.ModelViewSet):
model = BookModel
queryset = BookModel.objects.select_related('author').all()
serializer_class = BookSerializer
permission_classes = [
IsAccountAdminOrReadOnly
]
lookup_field = 'isbn'
{
"name": "Name",
"description": "Description",
"main": "index.js",
"authors": [
"Author"
],
"license": "ISC",
"moduleType": [],
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"jquery": "3.0.0-beta1",
"bootstrap": "v4.0.0-alpha.2",
"gsap": "greensock#^1.18.2",
"tether": "^1.1.1",
"font-awesome": "fontawesome#^4.5.0"
},
"overrides": {
"jquery": {
"main": [
"*/**/jquery.min.js"
]
},
"bootstrap": {
"main": [
"*/**/bootstrap.min.{js,css}"
]
},
"gsap": {
"main": [
"*/**/TweenMax.min.js"
]
},
"tether": {
"main": [
"*/**/tether.min.{js,css}"
]
},
"font-awesome": {
"main": [
"*/**/font-awesome.min.css",
"fonts/*.*"
]
}
}
}
gulp.task 'vendors', ->
jsFilter = gulpFilter '*.js',
restore: true
cssFilter = gulpFilter '*.css',
restore: true
fontFilter = gulpFilter '*.{otf,eot,svg,ttf,woff,woff2}',
restore: true
combiner(
gulp.src do mainBowerFiles
jsFilter
gulpIf isDevelopment, do sourcemaps.init
concat 'vendor.min.js'
gulpIf isDevelopment, do sourcemaps.write
gulp.dest path.build.js
).on 'error', handleError
combiner(
gulp.src do mainBowerFiles
cssFilter
gulpIf isDevelopment, do sourcemaps.init
concat 'vendor.min.css'
gulpIf isDevelopment, do sourcemaps.write
gulp.dest path.build.css
).on 'error', handleError
combiner(
gulp.src do mainBowerFiles
fontFilter
gulp.dest path.build.fonts
).on 'error', handleError
<h1>Hello</h1>
@Home = React.createClass
displayName: 'Home'
render: ->
`
<div className="main">
<nav className="nav">
<ul>
<li><a href=""></a></li>
</ul>
</nav>
</div>
`
this.Home = React.createClass({
displayName: 'Home',
render: function() {
return React.createElement("div", {
"className": "main"
}, React.createElement("nav", {
"className": "nav"
}, React.createElement("ul", null, React.createElement("li", null, React.createElement("a", {
"href": ""
})))));
}
});
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/reset.min.css' %}"/>
<link rel="stylesheet" href="{% static 'css/main.css' %}"/>
</head>
<body>
{% block header %}{% endblock %}
<script src="{% static 'js/main.js' %}"></script>
</body>
</html>
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block header %}
{% with txt='1' %}
{% include "layouts/header.html" %}
{% endwith %}
{% endblock %}
<header>
<p>{{ txt }}</p>
</header>
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block header %}
{% with txt='1' txt2='2' txt3='3' %}
{% include "layouts/header.html" %}
{% endwith %}
{% endblock %}
<header>
<p>{{ txt }}</p>
<p>{{ txt2 }}</p>
<p>{{ txt3 }}</p>
</header>
bundler = ->
browserify
entries: [ path.src.coffee ]
extensions: ['.coffee', '.js']
debug : true
.transform 'coffeeify'
.transform 'deamdify'
.bundle()
.on 'error', handleError
.pipe source 'main.js'
.pipe gulp.dest path.build.js
.pipe reload
stream: true
gulp.task 'coffee', ->
gulp.src path.src.coffee, read: false
.pipe plumber
errorHandler: handleError
.pipe tap bundler
define [], ->
"My string"
define ['./partials/extra'], (extra) ->
console.log "Returned: #{extra}"