Page not found – ShopingServer Wiki https://wiki.shopingserver.com Tutorials and Articles About Technology and Gadgets Wed, 02 Sep 2020 02:39:24 +0000 en-US hourly 1 https://wordpress.org/?v=5.5.14 https://wiki.shopingserver.com/wp-content/uploads/2018/07/cropped-favicon-150x150.png Page not found – ShopingServer Wiki https://wiki.shopingserver.com 32 32 Python: Get Today’s Current Date and Time https://wiki.shopingserver.com/python-get-todays-current-date-time/ https://wiki.shopingserver.com/python-get-todays-current-date-time/#respond Sat, 06 Jan 2018 09:29:37 +0000 http://wiki.shopingserver.com/?p=18535 H

ow do I find out the current date and time in Python? What is the module or function I need to use to get current time or date in Python programming language?

 

You can use time module (low level) which provides various time-related functions. However, this module is always available, not all functions are available on all platforms. Hence, you need to use the datetime (high level Object-oriented interface to dates and times) module in Python. It provides classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.

Getting current time in python using time module

The syntax is:

time.strftime(format)

24 hour format ##

time.strftime( %H:%M:%S )

12 hour format ##

time.strftime( %I:%M:%S )

Examples

A simple program in python to get today’s date and time:

#!/usr/bin/python

 

import time

print (time.strftime( %H:%M:%S ))

 

12 hour format ##

print (time.strftime( %I:%M:%S ))

Sample outputs:

23:46:08

11:46:08

To print current date use:

#!/usr/bin/python

 

import time

dd/mm/yyyy format

print (time.strftime( %d/%m/%Y ))

Sample outputs:

04/10/2013

GETTING LOCALS DATE AND TIME IN PYTHON

#!/usr/bin/python

 

import time

 

now = time.strftime( %c )

date and time representation

print  Current date & time   + time.strftime( %c )

 

Only date representation

print  Current date    + time.strftime( %x )

 

Only time representation

print  Current time   + time.strftime( %X )

 

Display current date and time from now variable

print ( Current time %s   % now )

Sample outputs:

Current date & time Sat Oct  5 00:04:59 2013

Current date 10/05/13

Current time 00:04:59

Current time Sat Oct  5 00:04:59 2013

Format strings

The following directives can be embedded in the format string:

Directive Meaning

%a Weekday name.

%A Full weekday name.

%b Abbreviated month name.

%B Full month name.

%c Appropriate date and time representation.

%d Day of the month as a decimal number [01,31].

%H Hour (24-hour clock) as a decimal number [00,23].

%I Hour (12-hour clock) as a decimal number [01,12].

%j Day of the year as a decimal number [001,366].

%m Month as a decimal number [01,12].

%M Minute as a decimal number [00,59].

%p Equivalent of either AM or PM.

%S Second as a decimal number [00,61].

%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.

%w Weekday as a decimal number [0(Sunday),6].

%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.

%x Appropriate date representation.

%X Apropriate time representation.

%y Year without century as a decimal number [00,99].

%Y Year with century as a decimal number.

%Z Time zone name (no characters if no time zone exists).

%% A literal ‘%’ character.

Get the current date and time in Python using datetime module

The syntax is:

now = datetime.datetime.now()

now.hour

now.mintue

now.year

now.day

now.month

Examples

#!/usr/bin/python

import datetime

i = datetime.datetime.now()

 

print ( Current date & time = %s  % i)

 

print ( Date and time in ISO format = %s  % i.isoformat() )

 

print ( Current year = %s  %i.year)

 

print ( Current month = %s  %i.month)

 

print ( Current date (day) =  %s  %i.day)

 

print ( dd/mm/yyyy format =  %s/%s/%s  % (i.day, i.month, i.year) )

 

print ( Current hour = %s  %i.hour)

 

print ( Current minute = %s  %i.minute)

 

print ( Current second =  %s  %i.second)

 

print ( hh:mm:ss format = %s:%s:%s  % (i.hour, i.month, i.second) )

Sample outputs:

Current date & time = 2013-10-05 00:15:31.769049

Date and time in ISO format = 2013-10-05T00:15:31.769049

Current year = 2013

Current month = 10

Current date (day) =  5

dd/mm/yyyy format =  5/10/2013

Current hour = 0

Current minute = 15

Current second =  31

hh:mm:ss format = 0:10:31

You can use date.strftime(format) to get a string representing the date, controlled by an explicit format string (see above table):

#!/usr/bin/python

 

from datetime import datetime

 

i = datetime.now()

 

print str(i)

 

print i.strftime( %Y/%m/%d %H:%M:%S )

Sample outputs:

2013-10-05 00:20:30.495228

2013/10/05 00:20:30

References:

See python time and datetime module for more info.

 

 

]]>
https://wiki.shopingserver.com/python-get-todays-current-date-time/feed/ 0
Python sleep(): Add Delay In A Seconds To Suspend Execution Of A Script https://wiki.shopingserver.com/python-sleep-add-delay-seconds-suspend-execution-script/ https://wiki.shopingserver.com/python-sleep-add-delay-seconds-suspend-execution-script/#respond Sat, 06 Jan 2018 08:53:21 +0000 http://wiki.shopingserver.com/?p=18491 I

am a new Python user. I would like to delay execution for five seconds in a Python script. How do I add a time delay in Python on Unix/Linux? Is there a sleep command in python like the Unix/Linux sleep utility to suspend execution of a bash script?

 

You need to import and use a module called time. This module provides various time-related functions for Python users.

Python sleep syntax

The syntax is as follows

import time

time.sleep(1)

time.sleep(N)

The time.sleep() suspend execution of a script for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

Example: Put delay in a Python script

Create a script called demo-sleep.py:

#!/usr/bin/python

# The following will run infinity times on screen till user hit CTRL+C

# The program will sleep for 1 second before updating date and time again.

 

import time

 

print  *** Hit CTRL+C to stop ***

 

Star loop ##

while True:

### Show today s date and time ##

print  Current date & time   + time.strftime( %c )

 

#### Delay for 1 seconds ####

time.sleep(1)

Save and close the file. Run it as follows:

$ chmod +x demo-sleep.py

$ ./demo-sleep.py

 

Sample outputs:

Fig.01: Python sleep() demo program output

Where,

Set an infinite loop using while True:

Get the current date and time using strftime() and display on screen.

Finally, add 1 second delay in a script using sleep(1).

Continue this procedure till user interrupts.

 

 

]]>
https://wiki.shopingserver.com/python-sleep-add-delay-seconds-suspend-execution-script/feed/ 0
How To Install Speedtest-cli On a CentOS / RHEL / Scientific / Fedora Linux To Check Internet Speed https://wiki.shopingserver.com/install-speedtest-cli-centos-rhel-scientific-fedora-linux-check-internet-speed/ https://wiki.shopingserver.com/install-speedtest-cli-centos-rhel-scientific-fedora-linux-check-internet-speed/#respond Fri, 05 Jan 2018 14:29:10 +0000 http://wiki.shopingserver.com/?p=18250 I

do not want to use Adobe flash based speed testing site due to security concern on my desktop. How do I install Speedtest-cli on a CentOS Linux or Fedora Linux or Red Hat Enterise Linux (RHEL) for checking the Internet speed?

 

Adobe Flash vulnerabilities are a major security issue for Linux users and speedtest.net use Adobe Flash. But, you can check the Internet speed with Python based CLI tool called Speedtest-cli. In this quick tutorial you will learn how to install speedtest-cli on a CentOS/RHE/Fedora/Scientific Linux desktop server or or laptop computer.

Step 1: Install python

Type the following yum command to install Python on a CentOS/RHEL/Scientific Linux:

$ sudo yum install python

 

Type the following dnf command to install Python on a Fedora Linux v22+:

$ sudo dnf install python

Step 2: Download speedtest_cli.py

Type the following wget command to grab the speedtest_cli.py client:

$ wget -O speedtest-cli https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py

$ chmod +x speedtest-cli

 

Fig.01: Grab speedtest_cli.py

Step 3: Check the Internet speed

Simply type the following command:

$ ./speedtest-cli

 

OR

$ python speedtest-cli

 

Sample outputs:

Retrieving speedtest.net configuration…

Retrieving speedtest.net server list…

Testing from nixcraft Dutch Holdings BV (5.151.xx.yyy)…

Selecting best server based on latency…

Hosted by SoftLayer Technologies, Inc. (Amsterdam) [6.45 km]: 2.317 ms

Testing download speed………………………………….

Download: 925.88 Mbit/s

Testing upload speed…………………………………………..

Upload: 105.69 Mbit/s

To see speed values in bytes instead of bits pass the –bytes option:

$ ./speedtest-cli –bytes

 

To generate and provide a URL to the speedtest.net share results image pass the –share option:

$ ./speedtest-cli –share

 

Of course, you can combine both the options:

$ ./speedtest-cli –share –bytes

 

Sample outputs:

Gif.01: Speedtest_cli.py in action

How do I specify a server ID to test against?

First, grab a server list, enter:

$ wget http://www.speedtest.net/speedtest-servers.php

 

To view a server ID, enter:

$ more speedtest-servers.php

 

To search a server ID, enter:

$ grep  city-name  speedtest-servers.php

$ grep  country-name  speedtest-servers.php

$ grep  Tampa, FL  speedtest-servers.php

<server url= http://speedtest1.hivelocity.net/speedtest/upload.php  lat= 27.9709  lon= -82.4646  name= Tampa, FL  country= United States  cc= US  sponsor= Hivelocity Hosting  id= 2137   host= speedtest1.hivelocity.net:8080  />

<server url= http://speedtestnet.rapidsys.com/speedtest/upload.php  lat= 27.9709  lon= -82.4646  name= Tampa, FL  country= United States  cc= US  sponsor= Rapid Systems  id= 1296   host= speedtestnet.rapidsys.com:8080  />

OR just display a server ID:

$ grep  Tampa, FL  speedtest-servers.php | egrep -o  id= [0-9]{4}

 

Sample outputs:

id= 2137

id= 1296

Next use the server ID 2137:

$ ./speedtest-cli –server 2137

 

Sample outputs:

Fig.02: speedtest-cli in action

Not a fan of speedtest.net?

No worries. Try wget, lftp or specilized tool like iperf on a Linux to test the Internet or Intranet speed from the command line.

 

 

]]>
https://wiki.shopingserver.com/install-speedtest-cli-centos-rhel-scientific-fedora-linux-check-internet-speed/feed/ 0
How to fix Httpoxy a CGI PHP/Nginx/Apache/Go application vulnerability on Linux or Unix https://wiki.shopingserver.com/fix-httpoxy-cgi-php-nginx-apache-go-application-vulnerability-linux-unix/ https://wiki.shopingserver.com/fix-httpoxy-cgi-php-nginx-apache-go-application-vulnerability-linux-unix/#respond Thu, 04 Jan 2018 08:11:18 +0000 http://wiki.shopingserver.com/?p=18103 A

serious vulnerability was discovered in how CGI scripts are used by Linux or Unix that use PHP, Go, Python, and other scripting languages. How do I fix Httpoxy a CGI application vulnerability on Linux or Unix for HAProxy, Varnish, Nginx, PHP, Go, Python, Tomcat and others?

 

httpoxy is a set of vulnerabilities that affect application code running in CGI, or CGI-like environments. It comes down to a simple namespace conflict:

RFC 3875 (CGI) puts the HTTP Proxy header from a request into the environment variables as HTTP_PROXY

HTTP_PROXY is a popular environment variable used to configure an outgoing proxy

This leads to a remotely exploitable vulnerability. If you’re running PHP or CGI, you should block the Proxy header. This attack use HTTP_PROXY for Man-in-the-Middle” attack. The following web servers, web frameworks and programming languages are affected:

Go lang (CVE-2016-5386)

PHP lang (CVE-2016-5385)

HHVM (CVE-2016-1000109)

Python (CVE-2016-1000110)

Apache Tomcat (CVE-2016-5388)

Servers Apache (CVE-2016-5387)/Nginx/Varnish/Httpoxy.

Disro – RHEL and CentOS and others.

Patch your OS and Apps

First install all available updates for your operating system and application software such as Apache, PHP, Nginx and more:

$ sudo apt-get update && sudo apt-get upgrade

 

OR

$ sudo dnf update

 

OR

$ sudo yum update

Httpoxy mitigation for Nginx proxy server

Edit your nginx.conf or fastcgi_params file:

# vi /etc/nginx/ fastcgi_params

 

Add the following directives:

fastcgi_param  HTTP_PROXY    ;

When proxying HTTP requests to an upstream application, it’s wise to set any Proxy header to the empty string, in case the upstream application is running on a vulnerable platform (added in your nginx.conf’s when load balancing and proxying HTTP traffic):

proxy_set_header Proxy   ;

Save and close the file. Reload/restart the nginx server:

# systemctl reload nginx

Httpoxy mitigation for Apache server

You can use mod_headers. Edit /etc/httpd/conf.d/site.conf or httpd.conf :

# vi /etc/httpd/conf.d/site.conf

 

Add the following directives:

RequestHeader unset Proxy

Save and close the file. Restart the apache server:

# systemctl restart httpd

 

http-request del-header Proxy

Httpoxy mitigation using HAProxy

Edit /etc/haproxy/haproxy.cfg and edit/append as follows to remove Proxy header:

http-request del-header Proxy

Restart the Httpoxy:

# systemctl restart haproxy

Httpoxy mitigation using Varnish

Edit the /etc/varnish/default.vcl and edit/append as follows to remove Proxy header (find and add in sub vcl_recv { … } section):

unset req.http.proxy;

Save and close the file. Restart the varnish:

# systemctl restart varnish

Httpoxy mitigation for PHP/Go lang cgi apps

You need to configure your web application firewall (such as Nginx) to remove the Proxy header from incoming HTTP requests. See above for Nginx and Apache proxy specific info.

Fixing your php app by editing .php file

Edit your PHP file and make sure he following statement near the top, after <?php:

<?php

/* Warning: Not tested and may not be effective */

putenv( HTTP_PROXY= ); $_SERVER[HTTP_PROXY] =   ;

 

/* NOTE */

/* If you are running PHP under Apache/mod_php, also add after the above: */

apache_putenv( HTTP_PROXY ,   );

 

/* rest of your php script */

Save and close the file.

Fixing your php app by editing go program file

Edit the following changes to your program as follows:

import  os

os.Unsetenv( HTTP_PROXY )

Verification

To fix the issue, temporarily install the following as a CGI script on your server and make it executable (say at /var/www/html/cgi-bin/test.cgi):

#!/bin/sh

echo  Content-Type:text/plain

​echo

echo  HTTP_PROXY= $HTTP_PROXY

Save and close the file. Make it executable:

chmod +x test.cgi

 

Call it as follows:

curl -H  Proxy: AFFECTED  http://your-server-ip-or-name/cgi-bin/test.cgi

 

If you see the following output, your server is unaffected:

HTTP_PROXY=

If instead you see the following, or any other output, your server may be affected and you should apply one of the mitigations as discussed above:

HTTP_PROXY= AFFECTED

References

For more information see https://httpoxy.org/ and httpoxy flaw info from Red Hat.

Apache HTTP server httpoxy security advisory.

Mitigating the HTTPoxy Vulnerability with NGINX

 

 

]]>
https://wiki.shopingserver.com/fix-httpoxy-cgi-php-nginx-apache-go-application-vulnerability-linux-unix/feed/ 0
Linux / Unix: “-bash: python: command not found” error and solution https://wiki.shopingserver.com/linux-unix-bash-python-command-not-found-error-solution/ https://wiki.shopingserver.com/linux-unix-bash-python-command-not-found-error-solution/#respond Thu, 04 Jan 2018 06:55:34 +0000 http://wiki.shopingserver.com/?p=18010 I

am a new user and trying to run Python program. I have a cloud based VM/VPS and when I type python mycode.py at the terminal of my server, I get the following error:

-bash: python: command not found

How do I solve this problem?

 

This error means Python is either not installed or your installation damaged. Here is how you can solve this problem.

Check for python path

Type any one of the following commands to see if python binary exists on a Linux or Unix-like system:

type -a python

 

OR

ls -l /usr/bin/python

ls -l /usr/bin/python*

 

OR

which python

 

Sample outputs:

Fig.01: Python command not found

 

It seems that Python is missing for an unknown reason or was not installed by your cloud provider to save the disk space. So install it as per your Linux distro or Unix variant:

Ubuntu/Debian/Mint Linux install Python

Type the following apt-get command or apt command

$ sudo apt-get install python

 

Or install python version 3:

$ sudo apt-get install python3

Oracle/RHEL (Red Hat)/CentOS Linux install Python

Type the following yum command:

$ sudo yum install python

Fedora Linux install Python

Type the following dnf command to add the Python v2.x:

$ sudo dnf install python

 

OR to add the Python v3.x:

$ sudo dnf install python3

Arch Linux install Python

Type the following pacman command to add the Python v2.x:

$ sudo pacman -S python2

 

OR add the Python v3.x:

$ sudo pacman -S python3

Suse/OpenSUSE Linux install Python

Type the following zypper command to add the Python v2.x:

$ sudo zypper install python

 

OR add the Python v3.x:

$ sudo zypper install python3

FreeBSD Unix install Python

Type the following pkg command to add the Python v2.x:

# pkg install python2

 

OR To install the Python v2.x port:

# cd /usr/ports/lang/python2/ && make install clean

 

To add the Python v3.x package:

# pkg install python3

 

OR To install the Python v3.x port:

# cd /usr/ports/lang/python3/ && make install clean

OpenBSD Unix install Python

Type the following pkg_add command to add the Python v2.x or 3.x:

# pkg_add python

 

OR

$ doas pkg_add python

 

Sample outputs:

quirks-2.241 signed on 2016-07-26T16:56:10Z

Ambiguous: choose package for python

a       0:

1: python-2.7.12

2: python-3.4.5

3: python-3.5.2

Your choice:

MacOS X Unix install Python3

Type the following command:

$ brew install python3

Verify Python installation

Type the following commands:

$ type -a python

$ which python

$ ls -l /usr/bin/python

$ ls -l /usr/bin/python*

 

Sample outputs:

Fig.02: Python installed on my OpenSUSE Linux box

A note about broken symlink

Sometimes a soft link to Pythons’s executables is broken for some reason. For example, /usr/bin/python3.4 is real executables. You can point /usr/bin/python to /usr/bin/python3.4 for Python version 3.4 using the ln command:

$ sudo ln -s /usr/bin/python3.4 /usr/bin/python

 

Now you can run program:

$ python mycode.py

 

 

]]>
https://wiki.shopingserver.com/linux-unix-bash-python-command-not-found-error-solution/feed/ 0
How to login with root password when using Ansible tool https://wiki.shopingserver.com/login-root-password-using-ansible-tool/ https://wiki.shopingserver.com/login-root-password-using-ansible-tool/#respond Wed, 03 Jan 2018 13:58:09 +0000 http://wiki.shopingserver.com/?p=17844 I

need to run a Linux command over 20 servers using a root user and password in Ansible too. How do I pass a user and password in Ansible over ssh based session? How can I set a default Ansible username/password for ssh connection?

 

There are two ways to solve this problem.

Method #1: Force username and password while using ssh

The syntax is:

export ANSIBLE_HOST_KEY_CHECKING=false

ansible –user {user} –ask-pass -i {inventory} {hostname} -a  command  -c paramiko

ansible –user root –ask-pass -i ~/myhosts www1 -a  uptime  -c paramiko

ansible –user root –ask-pass -i ~/myhosts cluster -a  /bin/date  -c paramiko

 

First create an inventory file using cat command:

$ cat inventory

[cluster]

ln.cbz01

ln.cbz01

ln.cbz01

ln.cbz01

 

For example, run date command on all hosts in cluster with root user and prompt for root user password, run:

$ export ANSIBLE_HOST_KEY_CHECKING=false

$ ansible –user root –ask-pass -i inventory cluster\

-a  /bin/date  -c paramiko

 

Sample outputs:

Fig.01: Setting up default Ansible username/password for ssh connection

 

Where,

export ANSIBLE_HOST_KEY_CHECKING=false : Host key checking enabled by default and it can be disabled with this option. Otherwise you may get an error that read as ‘The authenticity of host ‘ln.cbz01’ can’t be established.‘

–user root :Connect as root user for ssh.

–ask-pass : Ask for connection password for ssh.

-i inventory : Set inventory file name.

cluster : Set host names or variable

-a  /bin/date  : Run /bin/date command all given hosts

-c paramiko : Use paramiko module for ssh connection.

Please note that SSH keys are recommended but password authentication can be used as explained earlier. See method #2 below for more info on how to setup ssh keys for login.

A note about setting up the connection type and user on a per host basis in inventory file

The syntax is:

$ cat inventory

[cluster]

ln.cbz01 ansible_connection=ssh ansible_user=vivek

ln.cbz01 ansible_connection=ssh ansible_user=root

ln.cbz01 ansible_connection=ssh ansible_user=root

######### WARNING #################

never do the following i.e. never store

the root account ssh password to use in

a text file

####################################

ln.cbz01 ansible_connection=ssh ansible_user=root ansible_ssh_pass=foo

Method #2: Set and use ssh keys (recommended)

Create ssh keys if not created, run:

[ Set password for your keys ] ##

$ ssh-keygen -t rsa

[ Copy pub key to all remote boxes ] ##

$ ssh-copy-id -i $HOME/.ssh/id_rsa.pub root@ln.cbz01

$ ssh-copy-id -i $HOME/.ssh/id_rsa.pub root@ln.cbz02

$ ssh-copy-id -i $HOME/.ssh/id_rsa.pub root@ln.cbz03

$ ssh-copy-id -i $HOME/.ssh/id_rsa.pub root@ln.cbz04

[ Test it ] ##

$ ssh root@ln.cbz01

[ Set up SSH agent to avoid retyping passwords ] ##

$ ssh-agent bash

$ ssh-add ~/.ssh/id_rsa

[ Run ansible ] ##

$ ansible all -m ping

$ ansible -i inventory cluster -a  /bin/date

 

 

]]>
https://wiki.shopingserver.com/login-root-password-using-ansible-tool/feed/ 0
How To Install the Django Web Framework 2 on Ubuntu 16.04 https://wiki.shopingserver.com/install-django-web-framework-2-ubuntu-16-04/ https://wiki.shopingserver.com/install-django-web-framework-2-ubuntu-16-04/#respond Wed, 03 Jan 2018 11:25:49 +0000 http://wiki.shopingserver.com/?p=17706 D

jango 2.0 released. How do I install it on the Ubuntu Linux 16.04 LTS server? How do I create a sample “Hello world” view and /admin/ section for Django 2.x?

 

Django is a free and open source Python web framework for creating web apps. In this tutorial, you will learn how install Django 2 on an Ubuntu Linux 16.04 LTS server including a quick starter for your site.

Install the latest version of Django 2.x

First you need to install pip for Python 3.x. Type the following apt command/apt-get command

$ sudo apt-get install python3-pip

 

Sample outputs:

Reading package lists… Done

Building dependency tree

Reading state information… Done

The following additional packages will be installed:

binutils build-essential ca-certificates cpp cpp-5 dpkg-dev fakeroot g++ g++-5 gcc gcc-5 libalgorithm-diff-perl libalgorithm-diff-xs-perl libalgorithm-merge-perl libasan2 libatomic1 libc-dev-bin libc6-dev

libcc1-0 libcilkrts5 libdpkg-perl libexpat1-dev libfakeroot libfile-fcntllock-perl libgcc-5-dev libgdbm3 libgomp1 libisl15 libitm1 liblsan0 libmpc3 libmpfr4 libmpx0 libperl5.22 libpython3-dev

libpython3.5-dev libquadmath0 libstdc++-5-dev libtsan0 libubsan0 linux-libc-dev make manpages manpages-dev openssl patch perl perl-modules-5.22 python-pip-whl python3-dev python3-pkg-resources

python3-setuptools python3-wheel python3.5-dev rename xz-utils

Suggested packages:

binutils-doc cpp-doc gcc-5-locales debian-keyring g++-multilib g++-5-multilib gcc-5-doc libstdc++6-5-dbg gcc-multilib autoconf automake libtool flex bison gdb gcc-doc gcc-5-multilib libgcc1-dbg libgomp1-dbg

libitm1-dbg libatomic1-dbg libasan2-dbg liblsan0-dbg libtsan0-dbg libubsan0-dbg libcilkrts5-dbg libmpx0-dbg libquadmath0-dbg glibc-doc libstdc++-5-doc make-doc man-browser ed diffutils-doc perl-doc

libterm-readline-gnu-perl | libterm-readline-perl-perl python-setuptools-doc

The following NEW packages will be installed:

binutils build-essential ca-certificates cpp cpp-5 dpkg-dev fakeroot g++ g++-5 gcc gcc-5 libalgorithm-diff-perl libalgorithm-diff-xs-perl libalgorithm-merge-perl libasan2 libatomic1 libc-dev-bin libc6-dev

libcc1-0 libcilkrts5 libdpkg-perl libexpat1-dev libfakeroot libfile-fcntllock-perl libgcc-5-dev libgdbm3 libgomp1 libisl15 libitm1 liblsan0 libmpc3 libmpfr4 libmpx0 libperl5.22 libpython3-dev

libpython3.5-dev libquadmath0 libstdc++-5-dev libtsan0 libubsan0 linux-libc-dev make manpages manpages-dev openssl patch perl perl-modules-5.22 python-pip-whl python3-dev python3-pip python3-pkg-resources

python3-setuptools python3-wheel python3.5-dev rename xz-utils

0 upgraded, 57 newly installed, 0 to remove and 0 not upgraded.

Need to get 86.3 MB of archives.

After this operation, 245 MB of additional disk space will be used.

Do you want to continue? [Y/n] y

Get:1 http://archive.ubuntu.com/ubuntu xenial/main amd64 libgdbm3 amd64 1.8.3-13.1 [16.9 kB]

Get:2 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 perl-modules-5.22 all 5.22.1-9ubuntu0.2 [2661 kB]

….

..

Use the pip3 command as follows to install django

$ sudo pip3 install Django

 

OR

$ sudo pip3 install Django==2.0

 

Sample outputs:

Fig.01: Install Django 2.x using pip/pip3 command

 

Verify your installation by typing the following simple command:

$ django-admin –version

 

OR

$ python3 -m django –version

 

Sample outputs:

2.0

Creating user accounts for new project

Use the useradd command to create a new user named cbzdjango for my project:

$ sudo useradd -c  Cyberciti.biz app root  -d /home/httpd/ -m -s /bin/bash cbzdjango

$ sudo passwd cbzdjango

 

Where,

-c  description  : Set GECOS for the new account

-d /home/httpd/ : Set home directory for the new account

-m : Create home dir for the new account

-s /bin/bash : Set bash shell for the new account

Put your django 2.x code in some directory outside of the document root, such as /home/httpd instead of default /var/www/html. This is a security feature. Now you can login using ssh command or su command

$ ssh cbzdjango@server1.cyberciti.biz

 

OR

$ su – cbzdjango

Writing your first Django 2.x app

First you need to auto-generate some code that establishes a Django 2.x project using the django-admin command. The syntax is:

$ django-admin startproject Your-Project-Name-Here

$ cd Your-Project-Name-Here

 

For example, I am going to create a project named helloworld

$ django-admin startproject helloworld

$ ls -l

total 4

drwxrwxr-x 3 cbzdjango cbzdjango 4096 Dec  3 17:04 helloworld

$ cd helloworld

$ ls -l

total 8

drwxrwxr-x 2 cbzdjango cbzdjango 4096 Dec  3 17:04 helloworld

-rwxr-xr-x 1 cbzdjango cbzdjango  542 Dec  3 17:04 manage.py

Next you start the development server by typing the following command in the helloworld directory:

$ python3 manage.py runserver

 

Sample outputs:

Performing system checks…

 

System check identified no issues (0 silenced).

 

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.

Run  python manage.py migrate  to apply them.

 

December 03, 2017 – 17:13:44

Django version 2.0, using settings  helloworld.settings

Starting development server at http://127.0.0.1:8000/

Quit the server with CONTROL-C.

To change the server ip and port, run:

$ python3 manage.py runserver 8443

$ python3 manage.py runserver 0.0.0.0:8443

$ python3 manage.py runserver 10.98.222.14:8443

 

If you change the port and IP, make sure you update settings.py as follows to avoid the following error:

DisallowedHost at /

Invalid HTTP_HOST header:  10.98.222.14:8443 . You may need to add  10.98.222.14  to ALLOWED_HOSTS.

http://10.98.222.14:8443

Edit helloworld/settings.py

$ vi helloworld/settings.py

 

Set/update/edit ALLOWED_HOSTS as follows:

ALLOWED_HOSTS = [ 127.0.0.1 ,  localhost ,  192.168.2.115 ,  10.98.222.14  ]

Save and close the file. Start the server again:

$ python3 manage.py runserver 10.98.222.14:8443

 

Fire a web browser and type the following url:

http://10.98.222.14:8443

 

Sample outputs:

Fig.01: Yay! The install worked successfully on my server.

Writing your first view

First, make sure you’re in the same directory as manage.py and type the following command:

$ python3 manage.py startapp demo

$ ls -l

 

Sample outputs:

Fig.03: Creating the demo app

 

Above will create a directory demo, which is laid out like this:

demo

demo/models.py

demo/apps.py

demo/tests.py

demo/views.py

demo/migrations

demo/migrations/__init__.py

demo/admin.py

demo/__init__.py

This directory structure will hold the demo application. Next edit file as follows:

$ vi demo/views.py

 

Edit/append as follows:

from django.shortcuts import render

 

# Create your views here.

from django.http import HttpResponse

 

 

def index(request):

return HttpResponse( Hello, world. Yay! My first app is online. )

Save and close the file. This is the simplest view possible in Django and simple display “Hello, world. Yay! My first app is online.”. To call the view, you need to map it to a URL

$ vi demo/urls.py

 

Append the following code:

from django.urls import path

 

from . import views

 

urlpatterns = [

path(  , views.index, name= index ),

]

Save and close the file. Finally update urls.py in your project directory:

$ vi helloworld/urls.py

 

Edit/append as follows:

helloworld URL Configuration

 

The urlpatterns list routes URLs to views. For more information please see:

https://docs.djangoproject.com/en/2.0/topics/http/urls/

Examples:

Function views

1. Add an import:  from my_app import views

2. Add a URL to urlpatterns:  path(  , views.home, name= home )

Class-based views

1. Add an import:  from other_app.views import Home

2. Add a URL to urlpatterns:  path(  , Home.as_view(), name= home )

Including another URLconf

1. Import the include() function: from django.urls import include, path

2. Add a URL to urlpatterns:  path( blog/ , include( blog.urls ))

 

from django.contrib import admin

from django.urls import path

from django.conf.urls import include

 

urlpatterns = [

path( demo/ , include( demo.urls )),

path( admin/ , admin.site.urls),

]

Save and close the file. Start the server again:

$ python3 manage.py runserver 10.98.222.14:8443

 

Fire a browser and type the following command url:

http://10.98.222.14:8443/demo/

 

Sample outputs:

Fig.04: Your first “Hello World” app in Django 2.x in action

How to bootstrap the database and create /admin/ part for app

Type the following command to use the default sqlite3 db engine:

$ python3 manage.py migrate

 

Sample outputs:

Operations to perform:

Apply all migrations: admin, auth, contenttypes, sessions

Running migrations:

Applying contenttypes.0001_initial… OK

Applying auth.0001_initial… OK

Applying admin.0001_initial… OK

Applying admin.0002_logentry_remove_auto_add… OK

Applying contenttypes.0002_remove_content_type_name… OK

Applying auth.0002_alter_permission_name_max_length… OK

Applying auth.0003_alter_user_email_max_length… OK

Applying auth.0004_alter_user_username_opts… OK

Applying auth.0005_alter_user_last_login_null… OK

Applying auth.0006_require_contenttypes_0002… OK

Applying auth.0007_alter_validators_add_error_messages… OK

Applying auth.0008_alter_user_username_max_length… OK

Applying auth.0009_alter_user_last_name_max_length… OK

Applying sessions.0001_initial… OK

CREATING AN ADMIN USER

Type the following command:

$ python3 manage.py createsuperuser

 

Sample outputs:

Username (leave blank to use  cbzdjango ): admin

Email address: webmaster@cyberciti.biz

Password:

Password (again):

Superuser created successfully.

Start the development server, run:

$ python3 manage.py runserver 10.98.222.14:8443

 

Fire a Web browser and go to “/admin/” url on your local ip/domain:

http://10.98.222.14:8443/admin/

 

You should see the admin’s login screen:

Fig.05: /admin/ url in action

 

Type the admin username and password that you created earlier. You should see the admin section of the site as follows:

Fig.06: The admin site in action

Conclusion

And there you have it, Django 2.x installed on your Ubuntu Linux 16.04 server, working with a sample demo application. I suggest that you take a look at the following resources if you want to learn or master Django:

Django project home page

Django books for learning and mastering Django

Python 3 books for learning and mastering Python 3.x

 

 

]]>
https://wiki.shopingserver.com/install-django-web-framework-2-ubuntu-16-04/feed/ 0