Lamp linux apache mysql python

Установка связки Apache+MySQL+Python без фреймворка на сервер Ubuntu 14.04

Данное руководство покажет, как установить Python 3, MySQL и Apache2 без фреймворка. В результате вы сможете запускать базовую систему в производство.

Как правило, для работы с Python используется Django; этот фреймворк совместим со всеми версиями Python, поставляется с пользовательским сервером и даже позволяет установить базу данных в один клик.

Данное руководство будет пользоваться только менеджерами пакетов (apt-get и Pip).

Примечание: Менеджеры (или инсталляторы) пакетов – это небольшие программы, которые упрощают код установки и делают его более управляемым. Без них поддержка библиотек, модулей и остального кода была бы гораздо сложнее.

Требования

Чтобы следовать руководству, понадобится:

1: Настройка стандартной версии Python

Сначала нужно настроить Python 3 как стандартную версию, которая будет запускаться командой python.

Проверьте текущую стандартную версию Python.

На свежем сервере Ubuntu 14.04 результат будет таким:

Теперь нужно изменить текущую стандартную версию Python 3. Для начала удалите бинарные файлы Python 2.7:

Затем создайте символьную ссылку на бинарные файлы Python 3.

sudo ln -s /usr/bin/python3 /usr/bin/python

Снова проверьте текущую версию Python.

На экране должно появиться:

2: Установка Pip

Теперь можно приступать к установке Pip, менеджера пакетов Python. Сначала нужно обновить список пакетов системы, чтобы устаревшие пакеты не повлияли на установку.

Pip позволяет управлять всеми пакетами Python 3. Для установки менеджера пакетов Pip запустите:

sudo apt-get install python3-pip

3: Установка MySQL

На данном этапе нужно становить и настроить СУБД MySQL.

Система MySQL проста в установке:

sudo apt-get install mysql-server

Установите надёжный пароль для root-пользователя MySQL. Сервер MySQLбудет запущен сразу после завершения установки. Запустите:

Этот скрипт задаст ряд вопросов. Укажите только что созданный root-пароль. Скрипт спросит, нужно ли изменить root-пароль, но поскольку он был создан только что, введите n. В ответ на остальные вопросы можно просто нажать Enter, чтобы принять стандартные настройки.

Python 3 требует настройки для подключения к MySQL. Существует множество вариантов настройки (например, MySQLclient), но для простоты в данном руководстве используется pymysql. Установите этот модуль при помощи Pip:

sudo pip3 install pymysql

4: Установка Apache 2

Теперь нужно установить Apache 2 и убедиться, что веб-сервер распознаёт файлы Python как исполняемые.

Установите Apache с помощью apt-get:

sudo apt-get install apache2

Как и MySQL, сервер Apache запустится разу после установки.

Примечание: После установки веб-сервера появляются открытые порты.

Теперь нужно поместить root-каталог сайта в надёжную точку системы. Стандартный каталог находится в /var/www/html. Следуя конвенции, создайте тестовый подкаталог по имени test в этом каталоге.

В завершение нужно настроить взаимодействие Python и Apache. Отключите многопоточные процессы.

После этого предоставьте Apache расширенные права на запуск скриптов.

sudo a2enmod mpm_prefork cgi

Затем измените настройки Apache, чтобы явно объявить файлы Python как исполняемые и разрешить запускать их. Откройте конфигурационный файл с помощью nano или любого другого текстового редактора.

sudo nano /etc/apache2/sites-enabled/000-default.conf

После строки добавьте следующий код:


Options +ExecCGI
DirectoryIndex index.py

AddHandler cgi-script .py

Убедитесь, что блок помещён в блок .

/etc/apache2/sites-enabled/000-default.conf


Options +ExecCGI
DirectoryIndex index.py

AddHandler cgi-script .py
.

Этот блок Directory позволяет настроить поведение Apache для этого каталога. Он сообщает Apache, что каталог /var/www/test содержит исполняемые файлы, задаёт index.py в качестве стандартного файла и затем определяет исполняемые файлы.

Также нужно разрешить исполняемые файлы в каталоге сайта. Для этого измените путь для DocumentRoot. Найдите строку, которая начинается с DocumentRoot /var/www/html, и измените её:

Теперь файл имеет такой вид:

/etc/apache2/sites-enabled/000-default.conf


Options +ExecCGI
DirectoryIndex index.py

AddHandler cgi-script .py
.
DocumentRoot /var/www/test
.

Сохраните и закройте файл. Чтобы изменения вступили в силу, перезапустите Apache.

sudo service apache2 restart

Примечание: Apache 2 может вывести предупреждение о FQDN сервера. Его можно проигнорировать, так как директива ServerName еще не настроена.

Если в конце вывода находится строка [ OK ], Apache успешно перезапущен.

5: Тестирование настройки

Теперь нужно проверить, работает ли связка должным образом. Для этого создайте тестовую веб-страницу и БД.

Для начала создайте БД. Войдите в MySQL, введя root-пароль.

Теперь создайте тестовую БД (для примера назовём её example):

Добавьте таблицу для данных Python:

CREATE TABLE numbers (num INT, word VARCHAR(20));

Нажмите CTRL+D, чтобы выйти.

Затем создайте новый файл для простого приложения Python.

sudo nano /var/www/test/index.py

Скопируйте и внесите в него следующий код. В строке passwd укажите свой root-пароль MySQL.

#!/usr/bin/python
# Turn on debug mode.
import cgitb
cgitb.enable()
# Print necessary headers.
print(«Content-Type: text/html»)
print()
# Connect to the database.
import pymysql
conn = pymysql.connect(
db=’example’,
user=’root’,
passwd=’your_root_mysql_password’,
host=’localhost’)
c = conn.cursor()
# Insert some example data.
c.execute(«INSERT INTO numbers VALUES (1, ‘One!’)»)
c.execute(«INSERT INTO numbers VALUES (2, ‘Two!’)»)
c.execute(«INSERT INTO numbers VALUES (3, ‘Three!’)»)
conn.commit()
# Print the contents of the database.
c.execute(«SELECT * FROM numbers»)
print([(r[0], r[1]) for r in c.fetchall()])

Сохраните и закройте файл.

Затем установите права на новый файл.

Примечание: Более подробную информацию о правах можно найти в руководстве «Основы привилегий Linux».

sudo chmod 755 /var/www/test/index.py

При помощи браузера откройте http://ip_адрес_сервера. Появится такой вывод:

http://your_server_ip
[(1, ‘One!’), (2, ‘Two!’), (3, ‘Three!’)]

Заключение

Теперь сервер поддерживает Python 3 с надёжной базой данных на бэкэнде. Кроме того, управление пакетами стало гораздо проще, поскольку на сервере установлены удобные менеджеры пакетов.

Однако на данном этапе сервер несколько уязвим и требует дополнительной настройки. SSL-шифрование не является обязательным компонентом для работы сервера, однако это может значительно повысить уровень безопасности. Чтобы узнать, как получить и установить SSL-сертификат на веб-сервер Apache, читайте это руководство.

Источник

A Step by Step Guide to Install LAMP (Linux, Apache, MySQL, Python) on Ubuntu

If you want to get started building dynamic web applications on your Ubuntu machine, then chances are you will be wanting to use a LAMP stack to build and possibly deploy your work.

LAMP is an acronym that traditionally stands for “Linux, Apache, MySQL, and PHP,” which is a common server configuration for a lot of web applications. However, for the purposes of this article, we’re going to upgrade slightly to “Linux, Apache, MySQL, and Python,” since we’ll be swapping out PHP for Python as our programming language of choice. Also, in addition to MySQL as our database system, I will show you how to install and set up PostgreSQL, another popular and useful database system.

Step by Step Beginner

Linux

This procedure assumes that Ubuntu is already installed on your machine. If you need to install it, here are some very simple instructions on getting started.

After you have Ubuntu up and running, you’ll want to make sure that everything on your system is current. To do that, open the terminal and type in the following commands:

The result should look something like the screenshot below. Note that this and the following screenshots show the end of each command as it is completed, and so do not necessarily illustrate the entire process.

Updating Linux packages

Upgrading Linux packages

Note: You will have to confirm “yes” when running the “upgrade” command.

The first command is going to update the list of packages and their versions on your machine without going through the process of actually installing them. The second command installs the packages. For this reason, you should always run the update command first and then upgrade.

Installing Apache

The very heart of our LAMP stack is a piece of server software called Apache. A web server’s job is to process HTTP requests, which are used to send information across the Internet.

Why are we choosing Apache? Because it’s the world’s most popular web server software, it’s extremely stable, it’s well-supported, and it’s completely open source, which means you don’t have to pay anything for it.

To install Apache, type the following command into the Terminal:

sudo apt-get install apache2

Installing Apache

Voilà! You should now have a running web server on your machine. To check this, go to http://localhost/, where you should see a page saying “It works!”

Apache - It Works!

Installing Dependencies

There’s an additional step you’ll need to take to ensure that Apache and Python play together nicely: installing a tool called mod_wsgi. This is free tool for serving Python applications from Apache. You will also be installing a helper package called python-setuptools.

To install the tool and helper package, type the following command into the Terminal:

sudo apt-get install python-setuptools libapache2-mod-wsgi

Installing Python/Apache dependencies

You’ll need to restart your Apache server for mod_wsgi to load:

sudo service apache2 restart

Choosing Between MySQL and PostgreSQL

Next, you’ll want to install your database system. This can be a point of confusion for many people, because there are so many options out there, but I’m going to cover two of the most popular: MySQL and PostgreSQL. Unsure which to choose? Let’s take a look at each.

MySQL is the more common of the two. It’s relatively easy to install and get working. It’s also very well-supported by third-party tools, as well as by most web hosts. And it’s an extremely fast tool due to the fact that it doesn’t implement the full SQL standard, or as many data types as other solutions (in particular: PostgreSQL). This makes MySQL a great tool to use when writing simple applications that run fast and are easy to set up, but that don’t need to do anything too complex.

PostgreSQL, on the other hand, is a SQL-standards-compliant tool that supports many more data types than MySQL. It’s extremely powerful, and it’s designed to power complex applications. You can achieve much more in PostgreSQL than you can using MySQL. However, PostgreSQL is a bit more complicated to set up, and it’s comparatively less performant for simple operations due to its large feature set.

If you would like to see a full comparison between MySQL and PostgreSQL, DigitalOcean has written a wonderfully detailed article that should help in making the choice.

If you are a beginner and don’t actually understand the differences that have been outlined, just choose either one and play with it. The best way to learn which tools you do and don’t like is to try them out.

Installing MySQL

To install MySQL, type the following into the Terminal:

sudo apt-get install mysql-server

During the process of installing MySQL, you will be prompted to set a root password. This is the password you’ll use for the MySQL install. You can choose to set it now, or you can do so later, within the MySQL shell.

Set MySQL root password

After MySQL has finished installing, it starts automatically. To log into your server, use the following command (you will be prompted for your root password):

Logging into MySQL Server

From there, you can start to play with MySQL and set up new databases and users.

Installing PostgreSQL

To install PostgreSQL, type the following command into the Terminal:

sudo apt-get install postgresql

Installing PostgreSQL

To log into your server, use the following command (you will prompted for your user password):

Logging into PostgreSQL Server

After logging into your PostgreSQL server, you can start to set up new databases and roles.

Installing Python

The last step is installing Python. Since Ubuntu is our Linux distribution of choice, we have the luxury of having Python automatically installed for us. If you are curious about what version is currently installed, simply type this command into the Terminal:

Python in Ubuntu

The version info will be returned. Other than that, your Python installation should be good to go.

The Finish Line

Congrats! Just like that, you’ve installed an Ubuntu LAMP server. From here, you can start to play with Python, you can see how both MySQL and PostgreSQL store and retrieve data—and you can begin building your very own web applications.

Full-time web developer for Asana. When not obsessing over CSS I’m usually trying to surf somewhere in California.

Источник

Читайте также:  Таблицы
Оцените статью