WSGI mod, Python, Django, Celery and a nice fella virtualenv

Here I’ll show how to use Python (3.8.0 in the current example, but legit for latest 3.+ versions, not for os.name == ‘NT’) and virtualenv to setup WGSI enabled website on Django (or any) with implemented Celery + Flower + RabbitMQ. This example is my own path used for automated test framework: Octopus (not available now, but have dev branch opened: Lobster) Here only configurations and setup for Python 3.8.0, virtualenv, WSGI, Django, Celery (worker and beat services), Flower and that’s it. Later I’ll show Django + Celery configuration when they run together (sort of). You may want to install Python at first: Read When your modern and fancy python is installed, we’ll make a virtual environment for our website.Short Read more…

Centos Python Installation Guide with no Pain

Install Python on Centos 7 with make altinstall and without pain. Read more…

Test design and implementation.

Test design Our test system has a pretty simple configuration, so I do not want to bother you with the detailed description of it. Simply – it’s just a standalone execution of a test.py file with all requirements (test setup and tear down) in local internal test utility. Helper local utility has a usual amount of preparation functions, test data loading and some other configurations. In the very end of test loading, it just compares a node-set result of “real” scan (software and hardware nodes in a database after the scan) with predefined node-set (from test.py). Node set we usually expect at the end of the test should be added by the developer when product discovery pattern is ready orShort Read more…

Test automation or: How I Learned to Stop Worrying and Love Async __init__

octopus_main_page

Morning everybody… I recommend reading this part of the blog only in the morning with a cup of dark and strong coffee. I’ll show you some new cases, and howto’s to help you automate routines in the developer’s life. There will be an example of my fails and win on different scenarios. The poor code I’ll include also. Very beginning Firstly – I’ll try to make this thread in English. And maybe later when I have time – to make Ukrainian and Russian translations, I’ll make them. “Octopus” story has started from a small plugin for Sublime Text editor. Later it will be ported to Atom. I’ve started developing “Octopus” on spring-summer 2016, and I’ve not finished it yet! New functionsShort Read more…

Python – Django Celery – кейс длиною в вечность.

Вкратце: когда добавляешь пачку тасок на Celery worker’ы, случается так, что парочка из них отваливается или засыпает или еще чего. Долго не доходили руки поправить это недоразумение, поэтому я просто рестартовал все воркеры раз в пару дней или прямо перед началом проверки рутины, в общем очень сложно было поймать и воспроизвести тот случай, когда без каких-либо ошибок воркер просто молчал. И наконец дошоли руки запилить кривофикс, время покажет насколько он толковый, суть в следующем: В сразу после момента определения свободного воркера  – запускать app.control.heartbeat() и app.control.ping(timeout=10) и если ответ пришел (в виде [{‘alpha@host’: {‘ok’: ‘pong’}}]) – значит воркер готов и можно передавать ему таску, пачку тасков, рутину и тп. Если ответ пришел отличным от этого – даем ошибку и ничего не запускаемShort Read more…

Python 3 showing progressbar while subprocess.Popen

Have an interesting case I want to share and save for future. One small problem in this system: https://github.com/trianglesis/BMC_TPL_IDE is showing when some process is running and was not hanged up. Sometimes we need to run a huge amount of checks and tests and would be great to know if something hangs before killing it mannually. I used different scenarios and mostly a module pregressbar2, and this is what I finally can compose: Make worker which will execute job sorf of randomly: import time import random print(“START SOMETHING”) for i in range(5): sec = random.randint(1, 3) print(“Sleeping for: %d” % sec) time.sleep(sec) print(“Making job, line: %d” % i) print(“END SOMETHING”) Make process executor: import sys import subprocess import progressbar # DrawShort Read more…

VK_execute

Для всех страждущих наконец выкладываю нормальные примеры использования VK Script: https://github.com/triaglesis/vk_execute Там все мои примеры и по работе и просто тестовые. Самый быстрый вот такого плана, без внутреннего парсинга. Как только добавляешь внутрь вк скрипта какой-то проверочный код – КПД резко падает. Мой совет – вк_скрипт только для сбора всего “сырого” – дальше обрабатывать уже на сереверной стороне. var posts_cnt; var posts; var post_list = []; var offset_posts = Args.global_offset_posts; offset_posts = parseInt(offset_posts); // var offset_posts = 0; var run_count = 0; var iter_count = 20; while (iter_count > run_count ) {posts = API.wall.get( {“owner_id”:(Args.owner_id), “domain”:(Args.domain), “offset”:(offset_posts), “count”:”100″, “filter”:”all”, “extended”:”0″, “v”:”5.42″} ); post_list.push(posts.items); offset_posts = offset_posts + 100; run_count = run_count + 1; posts_cnt = posts.count; }; return {“posts_cnt”: posts_cnt,Short Read more…

Django, Apache2, Sublime Text 3 build system and developing process.

At first be sure that you are using this path to run pure apache: http://www.trianglesis.org.ua/django-python-3-4-wamp-apache-2-4-23-pycharm This topic for those who wants to develop ON THE FLY with python and django and do not want to manually restart dev server each time when code changes AND you don’t like built in python web-server and want to run your dev site as it should run on apache. Sublime Text 3 I use it for fast code changing and writting because PyCharm can’t work fine with multiline carrets, for example. Also PyCharm is too heavy when you want just copy&paste some features and see how it work on web. So my PyCharm will be used for debug purposes. I hope you know what isShort Read more…

Django + Python 3.4 + WAMP Apache 2.4.23 + Pycharm

Finally worked instance for hosting DEV site code on python and ability to resolve is as “on live” web server just on my laptop. A lot of different configurations changed but this is one working for me, and maybe can help you also. Better use EVERYTHING 32 bit for Window, you will suffer if you try to find some needed wheels for python 64bit on Windows 7 64bit.   WAMP Apache 2.4.23 Download: wampserver3.0.6_x86_apache2.4.23_mysql5.7.14_php5.6.25-7.0.10 Here NOTE: Install all needed C++ Redistr. packages which are listed in WAMP install guide! Download mod_wsgi.so Here or Here (for everythin 32 bit and python 3.4 on Win7 you need: mod_wsgi-py34-VC10.so) NOTE: Use mod_wsgi version which corresponds your python version! (Above in links you can find more info, justShort Read more…

Gjango, Pycharm – static files Windows

This topic for those who broke his mind trying to understand how to make Pycharm run Django with static files I’ve made it, but be carefull it can break your mind too! The settings I use the most portable way to configure settings – so I can move it into centos web server without paths changes Win\Unix (I HOPE). There are common DIRs BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # BASE DIR: D:\Projects\CODE\WEB\sites\www\smm_tools\smm_site PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) # PROJECT_ROOT:     D:\Projects\CODE\WEB\sites\www\smm_tools\smm_site\main_code STATIC_ROOT = os.path.join(BASE_DIR, ‘static’) #Static root:      D:\Projects\CODE\WEB\sites\www\smm_tools\smm_site\static STATIC_URL = ‘/static/’ Looks like ot works, but in really weird way: static files are working fine web page as template is loading some scc and js are loading and some are notShort Read more…

Домашний мох

Хочу записать какие виды мха сейчас пытаюсь выращивать. Некоторые виды завелись произвольно, так как были в грунте, другой же я принес специально из “рассадника” прямо на станции метро Университет. Там его целые поля растут, если кто знает какой это вид – скажите. Marchantia polymorpha L. (1753) – Маршанция полиморфная Bryum laevifilum Syed (1973) – Бриум гладконитевый или Funaria hygrometrica Hedw. (1801) – Фунария влагомерная И какой-нибудь Сфагнум, не могу определить его по фото. Варианты: Barbula convoluta Hedw. (1801) – Барбула свёрнутая   Bryum lonchocaulon Muell.Hal. (1875) – Бриум копьевидный     Взял отсюда: http://fotoflora.narod.ru/index01.html Read more…

Windows mirrored volume and hard reset

When you doing a hardware reset for Windows Server 2012 Hyper-V with RAID1 you may catch “Volume Sync” For me to remember: http://serverfault.com/questions/107636/how-to-view-status-of-software-raid-1-resynching Read more…

Пост с именинниками Вконтакте

Публикация поста с именинниками Вконтакте: Старый скриптец, который я использовал около года назад для выборки именинников и публикации поста с ними на стену сообществ Вконтакте. Выкладываю в публичный доступ, так как морально он устарел и код в нем выглядит ужасно, но подходит чисто для образовательных целей и “авось кому пригодится” мне бы он помог на первых порах изучения, может быть … Сам код можете смотреть здесь: В ближайшие дни, недели, месяцы я буду выкладывать все эти прошлые поделки, по мере того, как полностью перепишу их на новый манер, сейчас у меня основная задача – полностью унифицировать эти отрывки кода и сделать из них полноценную систему управления и автоматизации, поэтому, эти вот отрывки сами по себе уже никакой ценности не несутShort Read more…

Что значит код почистил:

Никаких тебе задержек, выполнение функций занимает менее секунды для краткой выборки, 3 секунды на выборку в цикле! 27-07-2016 – 18:37:53 Comments deleter: del_comments_regular – Will delete comment from non-member user(s): [266810306] 27-07-2016 – 18:37:53 Comments deleter: del_comments_regular – INFO: – Bot is finishing this iteration! Time spent: 3.870000123977661 27-07-2016 – 18:37:53 Comments deleter: =========================================================================================== 27-07-2016 – 18:38:15 Comments deleter: delete_comments_older – Will delete comment from non-member user(s): [1183178, 266810306] 27-07-2016 – 18:38:15 Comments deleter: delete_comments_older – INFO: – Bot is finishing this iteration! Time spent: 3.3279998302459717 27-07-2016 – 18:38:15 Comments deleter: =========================================================================================== 27-07-2016 – 18:39:07 Comments deleter: del_comments_regular – Will delete comment from non-member user(s): [266810306] 27-07-2016 – 18:39:07 Comments deleter: del_comments_regular – INFO: – Bot is finishing this iteration!Short Read more…

vk execute wall get comments automation

Как использовать vk execute для получения всех комментариев со всех постов? Как и обещал, пришло время выложить исходники (исподники) скриптов, которые я использую для собирания комментов с постов в группе. Суть в следующем, у вас есть группа, в которой есть посты, в которых есть комментарии. Вначале вы отбираете ТОЛЬКО те посты, в которых комментов больше нуля и формируете их них список, разделенный запятыми, это важно, так как метод вк не позволяет отправлять сразу список, поэтому мы его “обманем”. Порядок действий такой: получить все посты (wall.get) -> python отобрать посты, где комментарии > 0; -> python соорудить array из id постов, перевести его в строку: ‘11111,2222,3333,4444‘; -> python передать строку в execute-> python собрать с каждого поста комментарии; -> vk executeShort Read more…

Дилемма идиота

Что такое “дилемма идиота” для меня? Дилемма идиота это: привести ли весь свой говнокод в порядок и поставить его на новый модуль с хорошим, сложным и очень гибким планировщиком с БД и шлюхами, или перенести на временный легковесный модуль без БД за 5 минут, а пока все будет работать на легком модуле – плавно разбираться в более сложном но навороченном, или лучше вообще ничего не трогать и ну его нах? Inspired by: Легковесный планировщик: https://pypi.python.org/pypi/schedule/ Планировщик с блекджеком и шлюхами: https://pypi.python.org/pypi/APScheduler/ Read more…

Python schedule how to

Задачка на вечер: Дано: задание, которое нужно выполнять в заданные промежутки времени, модуль Python schedule. Задача: запускать одну и ту же задачу с разными значениями offset раз в 10 сек, так, чтобы 0ffset=119 запускался в 10 сек от начала каждой минуты, offset=219 на 20й секунде каждой минуты и так далее. Все что пока смог сделать – заставить выполняться задачу каждую 10ю секунду, НО! это грозит тем, что каждые 10 сек в очередь добавляется каждая след. задача, так что может выполняться все куда чаще, чем раз в 10 сек. Есть идея – сделать задержку в 10 сек после каждого добавления задачи в очередь, тогда может получиться задержка в 20 сек, потом выполнение подряд нескольких задач, и снова 20 сек задержки. СломалShort Read more…

Авто удаление комментариев Вконтакте

Автоматически удалять комментарии оставленные НЕ подписчиков группы? Модуль, который проверяет каждый оставленный комментарий в первых 10 и 50-100 постах на предмет того, оставлен ли он участником группы. Логика действий простая: получить все комментарии с айди (словарь вида: айди_коммента, айди_автора, время_коммента) авторов каждого комментария, проверить есть ли айди автора комментария в списке участников группы, если нет – составить список значений из списка словарей выше, далее запустить луп, в котором удалять каждый комментарий ил списка словарей комментариев, которые оставлены не участниками группы. Данная логика не рассматривает использование vk_execute, но в моем модуле он используется. Возможно, я расскажу именно о vk_script когда-нибудь позднее, когда закончу разработку всех мыслимых модулей, которые запланировал внедрить. На основе: http://www.trianglesis.org.ua/vk-execute-args-python-requests Последнее время работаю над системой, которая выполняет рутинноеShort Read more…

Oh my gosh BACULA config

Recently finished bacula config and run first one successfully! I’m really do not understand now, why does this tool have a complicated system with batch of daemons and modules. For my opinion, backup tool just should know from where to wherever make a backup and how often. But for further usage and remember this config, I’ll add it here.   Is is just a reminder, not a how-to, just want to not forget this. Job configs is not so complicate, intuitively understandable. Director bacula-dir.conf Concole bconsole.conf Storage basula-sd.conf File Daemon Client bacula-fd.conf       Read more…

Install Bacula on debian systems

Failed to load the database DBI driver SQLite at ./bacula-backup-lib.pl line 45 Based on: https://nklug.org.ua/node/23 http://www.microhowto.info/howto/connect_to_a_sqlite_database_using_perl_dbi.html https://ru.wikibooks.org/wiki/Bacula/Быстрый_старт http://help.ubuntu.ru/wiki/руководство_по_ubuntu_server/резервное_копирование/bacula https://www.digitalocean.com/community/tutorials/how-to-install-bacula-server-on-ubuntu-14-04 The main problem was: Failed to load the database DBI driver SQLite at ./bacula-backup-lib.pl line 45 this ultra fast fix can help: apt-get install libdbd-sqlite3-perl You can install any needed module based on SQL you use: MySQL, PostrgeSQL etc. Read more…