Pages

Tuesday, May 2, 2017

Python Flask installation , creating and delopyment of website

Python Flask installation , creating and deployment of website


Project location :


1. Install flask using pip



    pip install flask






2. Install virtualenv


    pip install virtualenv















3.Create a simple website ,


which has static css and js files


a.Create folder
b.Structure (final)


FlaskApp
  |-----------------------hello.py
  |-----------------------static -------|------ css --  main.css
                                        |------ js  – – datestuff.js
  |-----------------------templates –-----|-------hello.html
c. Create hello.py


#-*- coding: utf-8 -*- for apache webserver to under .it need in later part
# -*- coding: utf-8 -*-
#!/usr/bin/python

from flask import Flask
from flask import render_template
from datetime import datetime
from flask import request


app = Flask(__name__)

@app.route('/')
@app.route('/test')
def hello_world():
now = datetime.now()
rule = request.url_rule
return render_template('hello.html', name=now ,path=str (rule)
)


it is creating Flask app as “app” and routing / and /test .


It is calling a “hello template” by passing name as now (current date) and webroot as path




d. create html template file under tempate folder:hello.html


<!doctype html>
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='css/main.css') }}">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="{{ url_for('static',filename='js/datestuff.js') }}"></script>


</head>

<body>
<title>Hello from Flask</title>
{% if path == "/" %}
<h1>Home Page</h1>
{% endif %}
{% if name %}
<h1>Date from Pyton {{ name }}</h1>
<p> with out css </p1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}


<p id="demo"></p>


</body>


In header part , it is linking css and js required.




In body part , it is checking web path ,also displaying date which called by main python script .


e. create css and js files under static folder


css :
h1 {
display: block;
font-size: 1em;
margin-top: 0.67em;
margin-bottom: 0.67em;
margin-left: 0;
margin-right: 0;
font-weight: bold;
}


js
$(document).ready(function(){
var d = new Date();
document.getElementById("demo").innerHTML = ( "From JavaScript "+ d.toDateString());

});




js is setting date .








4.Run the website and access it



    export FLASK_APP=hello.py
    flask run

output :


* Serving Flask app "hell"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [03/May/2017 11:15:23] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [03/May/2017 11:15:24] "GET /static/css/main.css HTTP/1.1" 304 -
127.0.0.1 - - [03/May/2017 11:15:24] "GET /static/js/datestuff.js HTTP/1.1" 200 -




Access from browser


















4.Deploy in appache web server


a.install appache



    yum install httpd

b. Install mod_wsgi


    yum install mod_wsgi

c.copy the dev flask app folder to /var/www/ folder



    cd /var/www
    cp -r /code/FlaskApp .
  1. cd Flaskapp

d.create wgi file for apache
myapp.wgi


    vi myapp.wgi


# -*- coding: utf-8 -*-
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")

from hello import app as application



Here it is calling Flask app and imporing hello app as appliaction

e. Edit httpd.conf


    vi /etc/httpd/conf/httpd.conf

<VirtualHost *>
ServerName sterinlap.company.com

WSGIDaemonProcess yourapplication user=sterin group=sterin threads=5
WSGIScriptAlias / /var/www/FlaskApp/myapp.wgi

<Directory /var/www/FlaskApp/>
WSGIProcessGroup yourapplication
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
</VirtualHost>

WSGISocketPrefix /var/run/wsgi



In some linux version "WSGISocketPrefix /var/run/wsgi"   
is required 


f. Restart appache
  1. service httpd restart



5.Access in web







Saturday, April 22, 2017

Python script to monitor server,ports,Oracle Database ,website with email alerts



Python script to monitor server,ports,Oracle Database ,website with email alerts


Script location :




1. create server.txt



    vi server.txt


Format






## PING to ping server
#### PING <ServerName> <IP> <EmailIDs to alert> ## multiple IP can be provided with ","
## PING PORT , it will ping to port with server
#### PINGPORT <ServerName> <IP:PORT> <EmailIDs to alert>
## JDBCORCL to ping oracle DB using jdbc driver
#### JDBCORCL <DB INSTANCE> <IP:1521:orcl,Schename,Password> <EmailIDs to alert>
## URLPING to make http connection to URL
#### URLPING <ServerName> <URL> <EmailIDs to alert>





2. Create the message for alert email

Example :

HTML tags will work fine .














3. it uses JDBC driver for database connection . Make sure that java installed on the system to make DB connection .


https://github.com/sterin501/PythonScripts/tree/master/MonitorScirpt/oracleDBConn




4. Add the script in crontab with monitor period




Thursday, March 23, 2017

How to install and build python application in linux?


How to install and build python application in linux?


This topic installing and creating simple server based on python


1. Install python



    yum install python



2. Install pip for python .
Epel repo required

    wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
rpm -ivh epel-release-latest-6.noarch.rpm

    yum install python-pip




3. install rpyc for server . ( to check pip)






    pip install rpyc


with proxy
    pip install rpyc –proxy=http://<IP:PORT>




4 . pyinstaller to create executables


This is for python 2.6.2 . This is default for RHEL 6 . For python 2.7 pip works for pyinstaller


    wget https://pypi.python.org/packages/c3/a3/d50648bc99a8d5d6c533fc5c1101cc18014d0782e7ddbe9744ad2d56ad49/PyInstaller-2.1.tar.gz


extract the file
    python setup.py install








5. Test the script


Create simple python file


#!/bin/python


print 'TEST'
as test.py



    ./pyinstaller.py --onefile /tmp/new.py




it will create , exe under dist folder




6. Creating simple server with logger in python


myserver.py
#!/bin/python
import rpyc,logging,logging.handlers
from rpyc.utils.server import ThreadedServer




LOG_FILENAME = '/tmp/monitorServer.log'
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(message)s")
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=1024, backupCount=5)
handler.setFormatter(formatter)


my_logger.addHandler(handler)








if __name__ == "__main__":
server = ThreadedServer(MyService, port = 18812)
my_logger.info(" Listening at 18812")
server.start()




This will create server running on 18812






7. Build server



    ./pyinstaller.py --onefile myserver.py




8. Adding as service to start when ever server starts


a. Create script under /etc/init.d


#!/bin/bash
# chkconfig: 345 99 10
# description: my Monitor server based on Python
#
case "$1" in
'start')
/opt/myserver 2>/tmp/mm_error.log &;;
'stop')
echo "put something to shutdown or kill the process here";;
esac
as myserver under /etc/init.d
Where /opt/myserver is the server exe
Other options are default




8. Adding chkconfig

    chkconfig --add myserver
  1. chkconfig --list myserver



After reboot check the port to verify server is running or not