Category Archives: Web Development

Язык программирования Go

Посоветовали обратить внимание на этот язык программирования Go.

Выглядит с первого взгляда как некий апгрейд языка C с добавлением garbage collection, type safety, dynamic typing, variable length arrays, key-value maps, large standard library. Нет наследования как в C++, но есть композиция и интерфейсы. Более быстрая компиляция, чем в C++ и лучше поддержка многопоточности.

https://en.wikipedia.org/wiki/Go_(programming_language)

Using SCP instead of FTP

scp

I tried to delete a folder that contained tons of localization folders and waited for a very long time, since I was using FTP client and it was very slow during deleting and copying folders with massive amount of subfolders and files. That is why I decided to find another way to delete and copy files faster to the remote server from my local computer.

Secure copy or SCP is a means of securely transferring computer files between a local host and a remote host or between two remote hosts. It is based on the Secure Shell (SSH) protocol.

SCP is more secure that plain FTP. It also allows to copy directly to the given folder on server, if permissions granted. FTP allows to copy only to the FTP folder.

AP_scp

These are the commands.

To copy files from server to your local machine:

To copy files from your local machine to the server:

To go to the folder with a folder, that will be copied (in my case it is common-app-server folder):

To archive a folder, so that not to include Mac OS X system files like .DS_Store

To remove a folder from server before copying a new version:

To copy zip file using SCP:

Here root is a user name, that has permission to write to the destination folder.
lovecakes.ru – server name
/var/www/den.ladby.ru/public – destination folder

To install zip on server:

To unzip copied folder on server:

To remove MACOSX folder:

To remove zip file on server and local machine after unzipping:

To copy a folder without archiving:

Sending iOS Push Notifications using Python module PyAPNS

python-django

I have written a small module, that sends a push notification using PyAPNS.

This is how my sender.py module looks like:

Here is a Sender class inside sender.py module. It has one method send. Inside this method I create an object of APNs class, create a payload and send it using this object.
Cert.pem and Key.pem files are inside the folder with this module. They can be created using this tutorial. Also that folder contains apns.py module file with PyAPNS code.

To send a sample push notification from a command line I use following commands. First, I enter the folder with module. It is called notification_sender:

Or on server:

Then I enter to the python console:

Then I import Sender class from sender module:

Create a sender object of a Sender class:

And finally send a notification:

All you need to do to finish the job is to enter a PEM pass phrase:

Currently, the device token is hardcoded, I am planning to use SQLite entries with collected tokens. I use Django to collect tokens.

I would like to add that if you change somehow the source file of a module, you should reenter python console and recreate object to make changes work.

Django – some frequently used commands

python-django

While working with Django you use a lot of commands. I decided to create a list of commands for myself to make my development a little faster.

Quick links to tutorials:

My project folder is this: ~/Documents/common-app-server/app_server

My project name is: tokens

Creating virtual environment:

Activating virtual environment:

Installing Django on virtual environment:

Django version:

Starting a project:

Creating Django application:

Syncing database for the first time:

Creating migrations:

Looking at migrations:

Starting migrations:

Entering sqlite mode:

Recreating database:
1. Delete migrations folder
2. Use this command to clear database:

3. Create and run migrations

Running a local server:

Creating admin user:

App view:

Admin view:

Installing DjangoRestFramework:

Running Django project on Apache production server with mod_wsgi

django

This is official tutorial. But it didn’t work for me for 100 %. But there is some useful information on wsgi and daemon process that should be created.

There is a good tutorial, that I followed and it actually works. But I decided to write my own post with instructions for my personal project:

First we enter the production server via SSL and create a virtual environment there:

Then we activate it:

Check the Django version. It must be the same as in your local server:

Save somewhere a path to a Django project:

Your path will be different.

This is an example of a sites-available/*.conf file setting to run Django with WSGI:
Снимок экрана 2014-09-19 в 20.25.49

Here app_server is the name of my Django project or you can name it a site. But in my case it is not site but server for a mobile application.

Python and Django version on server and virtual environment may be different. You should do everything inside virtual environments with the same versions on local and production servers.

Installing Django on Mac

django

First you should install Python and Pip:

Then you install virtual environments:

And activate one virtual environment:

Then you install Django using pip in that virtual environment. Don’t use sudo, since if you use it, then you will install Django not in virtual environment but in common environment.

Now you can start creating Django projects using this tutorial.

To look at a version of installed Django use this:

To create a project:

To activate database:

To run a server:

To open your first project on Django:

5 недостатков, по которым облачные сервисы совсем не подходят для стартапа

1

Существует распространенный миф, что в наше время можно разрабатывать IT стартапы без вложений, пользуясь различными облачными PAAS сервисами (platform as a service). Этот миф, в частности, высказал Гай Кавасаки на своей лекции об ошибках предпринимателей. Но я с этим не согласен и вот почему.

1. Распределенность облаков не нужна стартапам. Например, на GAE (Google App Engine) база BigTable – реализация NoSQL, а не какой-нибудь обычный SQLite. NoSQL, как оказалось, крайне не удобен. Он позволяет создавать распределенную базу данных, но не позволяет очень много других вещей, с которыми обычные SQL базы справляются легко. При этом стартапу совсем не нужна распределенность в ущерб возможностям – у него еще даже нет клиентов и больших данных.

2. Стартапам крайне вредны ограничения, возникающие из-за использования SandBoxes. На GAE все веб-приложения работают в закрытых sandboxes, что создает ограничения при использовании различных API, например, нельзя сохранять файлы в файловой системе. Нельзя легко и просто работать с многопоточностью. Такого рода ограничения недопустимы при создании инновационных продуктов, когда нужно преодолевать границы невозможного.

3. Облачные сервисы на самом деле не бесплатны. На GAE меня попросили включить Billing, чтобы воспользоваться библиотекой для работы с SSL фреймворками Python. При этом заранее не предупредили, что SSL будет платным. Я это узнал только когда уже все сделал и решил насладиться работой своего веб приложения. В Amazon EC2 меня попросили заплатить 15 $ за неработавший сервер, на котором я только тестировал один из стартапов еще в прошлом году. Они включили мне автоматически биллинг через год бесплатного пользования.

4. Стартапу не нужен хороший SLA за большие деньги. SLA – Service Level Agreement задает высокую надежность вашему приложению, что является плюсом облачных сервисов. Но стартапу не нужна высокая надежность серверов в ущерб дороговизне их содержания.

5. Сервер на облаке не похож на ваш компьютер в плане среды для приложения. На Development сервере (то есть локальном компьютере) не всегда полностью воспроизводится среда, которая будет на Production, так как там есть свои многочисленные ограничения, некоторые из которых я назвал выше. Следовательно, быстро развернуть что-то не получится. Надо будет отказываться от каких-то функций, что-то переписывать. А стартапу важна скорость разработки и развертывания.

Итог и мой совет.
Я решил полностью прекратить попытки использовать облака и решил переключиться на выделенный сервер, на котором все можно и при этом бесплатно – платишь только некое подобие абонентской платы ежемесячно, не боясь потратить слишком много.

К сожалению, чтобы понять это, у меня ушло несколько дней и я написал уже довольно много кода для GAE. Не повторяйте моей ошибки.

Searching for the best technology for a mobile app backend development

Client-server applications with a mobile app client are more interesting than mobile standalone applications. They offer a new type of features for users like daily updated content. That is why at some moment of my mobile developer career I decided to learn how to create a server side for my mobile applications myself. As it happens usually in IT, there were a lot of techologies and programming languages, that I could start to learn and use for achieve my goals. Of course, if I would stop on the first one, that I have tried, I would lose, because one can never find the best way without understanding what other ways give and without any broad enough knowledge. I think, it is a good idea to get familiar with minuses of each technology before starting to learn and use it.

This is my story. I started with Java Servlets and I have tried also PHP and Python at the moment. Also I have read about Ruby On Rails and Node.JS. Finally, I stopped currently at using Python with Django.

Between Java Servlets and Python I choose Python. Development on Python it is much faster than on Java Servlets. It has no complex and sensible configuration files. Python offers iterative development, you can just refresh a web page and see results instantly. With Java Servlets you have to wait some time every time you update something. Python is like scripting language, despite it is compiled to some kind of byte code. I also liked python for it’s clean syntax, despite I am friendly with Java too. Using HTML templates with Python is easier to me, than creating JSP pages with servlets. Just for information, I use Sublime Text 2 as a Python editor with a Lazy color theme. It is really convenient editor.

I will not try PHP, because it is not valuable now, loses it’s popularity. It looks like Python offers almost the same features but even is better because of syntax, because it is compiled and because it offers full OOP support from the start and you can create all kind of applications including desktop applications with it. Also there are a lot of scientific and data analysis libraries on Python, that can be useful to create sophisticated back-end.

I don’t like the idea of using generally considered to be slow Javascript at the backend in Node.js. Also Node.js needs it’s own HTTP server.

What about Parse, QuickBlox and other ready for use backend services? I don’t want to use them, because I want to be able to create my own-backends with complete understanding of their code and work. These are good to create something easy and usual, but not something unique.

Probably I will try also Ruby on Rails at some moment.

But currently I am completely satisfied with Python. I want to get familiar with Django framework on Python too.

There are also open-source backends like Baasbox: http://www.baasbox.com/. But I haven’t tried it yet. Looks like it is written on Java, because needs JVM.

More articles on this topic:

http://www.raywenderlich.com/20482/how-to-choose-the-best-backend-provider-for-your-ios-app-parse-vs-stackmob-vs-appcelerator-cloud-and-more

http://www.developer-tech.com/news/2013/feb/22/exploring-mobile-app-backend-options/

Solution for: browser won’t load certain websites on a Mac

In many cases, this problem occurs, when a browser can’t resolve a host. I.e. it cannot find an IP address for a certain domain name in DNS servers. This happens, when your provider is too slow in updating DNS entries from all over the world when they are changed by administrators of web sites.

In case your browser won’t load certain websites, you can try to add DNS entries for those sites manually in your hosts file. To do this do the following:

1. In Terminal type the following:

so that you begin to edit your hosts file

2. Enter the password for your admin user on your mac.

3. Press “I” to enter Insert mode in Vim.

4. Go to the end of file and type IP addresses and corresponding domain names:

5. Press Esc. And type “:wq” to save and exit from vim.

6. Ready! You can now try to open your web sites.

If you don’t know IP address for your site, you can ping it on some other computer to determine the IP address or use web sites for this purpose to determine IP by domain name. For example, this one.

How to find an e-mail in Ubuntu, that appears in logs

I had a problem on Ubuntu server. Some guy has added his e-mail somewhere and the server tried to send him e-mails. So Google responded, that it was spam and blocked them. I have searched using grep in logs this way:

And got this kind of entries in mail.log and others:

For a while I couldn’t find a problem place and didn’t know, where to fix. I tried to list cron jobs:

But without a success.

Finally, I did search using grep recursively and found some files, where this e-mail appeared:

Because it was in *.db files, I couldn’t fix it by just editing config files in PostFix.

And because PostFix is not used in the server, I just removed it: