Thursday, December 28, 2017

html / javascript : Make elements visible / hidden on drop down values

 Make elements visible / hidden on drop down values


<html>
Display Element
<select id="display" name="form_select" onchange="showDiv()">
   <option value="no">No</option>
   <option value="yes">Yes</option>
</select>
<div id="hidden_div" style="display:none;">Hello hidden content</div>

<script type="text/javascript">
    function showDiv()
    {
       if(document.getElementById('display').value=="yes")
        document.getElementById('hidden_div').style.display = "block";
        else
        document.getElementById('hidden_div').style.display = "none";
    }
</script>
</html>

Wednesday, December 27, 2017

Python : Flask accept data from user (POST)

Flask Accept data from user

Pre - Req :

1. Make sure u have installed Flask module , Requests module 
2. Currently using Liclipse as python IDE

Example 1 :
To accept data from user ( post request ) and display result in same page

----------------------Paste below code inside Your_Project/templates/vote.html------------------------------
<html>
   <body>
        <form action=""  method = "POST">
            <p>Enter Name : <input name="name" type="text" /></p>
            <p>Enter Age :<input name="age" type="text" />&nbsp;</p>
            <! note : button should always be type ="submit">
            <p><input name="OK" type="submit" value="submit" /></p>
        </form>

        {% if name %}
            <p><strong>{{name}} is {{eligible}} to vote</span></strong></p>
        {% endif %}

   </body>
</html>
--------------------------------------------------------------------------------------------------------

from flask import request,Flask,json,render_template
from flask.json import jsonify
app = Flask(__name__)

@app.route('/')
def vote():
    return render_template('vote.html')

@app.route('/',methods=['POST'])
def vote1():
    result1 = request.form
#input fields values are stored as dictionary  and key = input name given in html

    if (int(result1['age'])>=18):
        eligible="is eligible"
    else:
        eligible="is not eligible"
    return render_template("vote.html",name=result1['name'],eligible=eligible)

if __name__ == "__main__":

    app.run(host='0.0.0.0', port=1111 , debug=True)#http://localhost:1111/"

Steps :
1. Run the above code
2. Open browser
3. Open http://localhost:1111/  or http://your_sytem_name:1111

Example 2 :
To accept data from user ( post request ) and display result in different page

----------------------Paste below code inside Your_Project/templates/vote2.html-----------------------------
<html>
   <body>
        <form action="http://den01bro.us.oracle.com:1111/result"  method = "POST">
            <p>Enter Name : <input name="name" type="text" /></p>
            <p>Enter Age :<input name="age" type="text" />&nbsp;</p>
            <! note : button should always be type ="submit">
            <p><input name="OK" type="submit" value="submit" /></p>
        </form>
   </body>
</html>
-------------------------------------------------------------------------------------------------------------------------
from flask import request,Flask,json,render_template
from flask.json import jsonify
app = Flask(__name__)

@app.route('/<string:name>')
def temp(name):
    return render_template('vote2.html')

@app.route('/result' ,methods=['POST'])
def temp2():
    result1 = request.form
    if (int(result1['age'])>=18):
        eligible="is eligible"
    else:
        eligible="is not eligible"
    return (result1['name']+" "+eligible)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=1111 , debug=True)#http://localhost:8000/"

Steps :
1. Run the above code

2. Open browser
3. Open http://localhost:1111/any_string  or http://your_sytem_name:1111/any_string_here


Example 3:
Adding example 1 + example 2 , ie., 

scenario 1 : If user opens http://localhost:1111/  , User will get result in the same page.
scenario 2 : If user opens http://localehost:1111/any_string , User will get result in different page .

----------------------Paste below code inside Your_Project/templates/vote.html------------------------------
<html>
   <body>
        <form action=""  method = "POST">
            <p>Enter Name : <input name="name" type="text" /></p>
            <p>Enter Age :<input name="age" type="text" />&nbsp;</p>
            <! note : button should always be type ="submit">
            <p><input name="OK" type="submit" value="submit" /></p>
        </form>

        {% if name %}
            <p><strong>{{name}} is {{eligible}} to vote</span></strong></p>
        {% endif %}

   </body>
</html>
----------------------Paste below code inside Your_Project/templates/vote2.html-----------------------------
<html>
   <body>
        <form action="http://den01bro.us.oracle.com:1111/result"  method = "POST">
            <p>Enter Name : <input name="name" type="text" /></p>
            <p>Enter Age :<input name="age" type="text" />&nbsp;</p>
            <! note : button should always be type ="submit">
            <p><input name="OK" type="submit" value="submit" /></p>
        </form>
   </body>
</html>
-------------------------------------------------------------------------------------------------------------------------
from flask import request,Flask,json,render_template
from flask.json import jsonify
app = Flask(__name__)

@app.route('/')
def vote():
    return render_template('vote.html')

@app.route('/',methods=['POST'])
def vote1():
    result1 = request.form
    if (int(result1['age'])>=18):
        eligible="is eligible"
    else:
        eligible="is not eligible"
    return render_template("vote.html",name=result1['name'],eligible=eligible)

@app.route('/<string:name>')
def temp(name):
    return render_template('vote2.html')

@app.route('/result' ,methods=['POST'])
def temp2():
    result1 = request.form
    if (int(result1['age'])>=18):
        eligible="is eligible"
    else:
        eligible="is not eligible"
    return (result1['name']+" "+eligible)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=1111 , debug=True)


Example 4:
Accept 2 input from a html file and display same value into another html .

----------------------Paste below code inside Your_Project/templates/input_data.html--------------------
<form action="{{ url_for('submit') }}" method="post">
    <textarea name="text"></textarea>
<textarea name="text2"></textarea>
    <input type="submit">
</form>
----------------------Paste code in Your_Project/templates/output_2data.html--------------------
<p>text1&nbsp;<input name="text1" type="text" value={{text1}}/></p>
<p>text2&nbsp;<input name="text2" type="text" value={{text2}}/></p>
----------------------input_data2.py----------------------
from flask import Flask, request, render_template

app = Flask(__name__)
@app.route('/')
def index():
    return render_template('input_data.html')

@app.route('/submit', methods=['POST'])
def submit():
    data=request.form
    data1=data['text']
    data2=data['text2']
    return render_template("output_2data.html",text1=data1,text2=data2)
    #return 'You entered: {}'.format(request.form['text'])

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8003)
-------------------------------------------------------------------------------------------------------------------------

Monday, December 11, 2017

python : Flask Basic

Flask (Python WebFramework )

Pre Req :
1. make sure python is installed in your system
2. pip install flask in terminal or cmd line.(python package installer)
Note:
1.         Default method =GET (if not mentioned)
2.         Use ARC , Postman etc., to make post statements
3.         “submit” button in html triggers post.

Use host="0.0.0.0" and port forward when using with docker
Example #app.run(host='0.0.0.0', port="5432",debug=True)
https://medium.com/@umerfarooq_26378/web-services-in-python-ef81a9067aaf


Html Template :

from flask import request,Flask,json,render_template

app = Flask(__name__)


@app.route(“/resource”)

Def xxx(resource)

                        ….

                        …..

if __name__ == "__main__":

    app.run(host='0.0.0.0', port=1234 , Debug=true)

Passing Args

#http://localhost:1234/hello?name=Luis

@app.route('/hello')

def api_hello():

    if 'name' in request.args:

        return 'data: ' + request.args['name']

    else:

        return 'Data: no data'

Any Resource

'''http://localhost:1234/any_string

@app.route("/<string:name>/")

def string_var(name):

    return "string_variable: "+name


Any Resource displaying html

#http://localhost:1234/random_string

#make sure “templates” folder is created insede project with image.html

@app.route("/<string:name>/") #<int:value>

def hello(name):

    return render_template('image2.html', name=name)

All Methods

''' GET/POST/PATCH/PUT/DELETE

   http://localhost:1234/verb ‘’’

@app.route('/verb', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])

def api_echo():

    if request.method == 'GET':

        return "verb: GET\n"

    elif request.method == 'POST':

        return "verb: POST\n"

    elif request.method == 'PATCH':

        return "verb: PACTH\n"

    elif request.method == 'PUT':

        return "verb: PUT\n"

    elif request.method == 'DELETE':

        return "verb: DELETE"


POST with body in REST

'''example

POST   http://localhost:1234/messages

H "Content-type: application/json"

-body '{"message":"Hello Data"}'

'''

@app.route('/messages', methods = ['POST'])

def api_message():

    if request.headers['Content-Type'] == 'text/plain':

        return "Text Message: " + str(request.data)

    elif request.headers['Content-Type'] == 'application/json':

        return "JSON Message: " + json.dumps(request.json)

    else:

        return "returns raw data:"+request.get_data()


POST accept from Html and send to html

Note:

1.         submit button in html to trigger POST

2.         Save html code in Project/templates/name.html

3.         Use Javascript inside html to manipulate data.

4.         Data is received to flask as dictionary

5.         Python data accessed in html as “{{}}”

6.         “url_for” used instead of “http://localhost:8003/submit”

input_data.html

<form action="{{ url_for('submit') }}" method="post">

    <textarea name="text"></textarea>

 <textarea name="text2"></textarea>

    <input type="submit">

</form>

output_2data.html

<p>text1&nbsp;<input name="text1" type="text" value={{text1}}/></p>

<p>text2&nbsp;<input name="text2" type="text" value={{text2}}/></p>

input_data2.py

from flask import Flask, request, render_template


app = Flask(__name__)

@app.route('/')

def index():

    return render_template('input_data.html')


@app.route('/submit', methods=['POST'])

def submit():

    data=request.form

    data1=data['text']

    data2=data['text2']

    return render_template("output_2data.html",text1=data1,text2=data2)

    #return 'You entered: {}'.format(request.form['text'])


if __name__ == "__main__":

    app.run(host='0.0.0.0', port=8003)


 Error handle

@app.errorhandler(404)

def not_found(error=None):

    message = {  'status': 404,  'message': 'Not Found: ' + request.url}

    resp = jsonify(message)

    resp.status_code = 404

    return resp


Friday, November 24, 2017

Python : Pretty print JSON

Pretty print JSON 

 

import json
 

json_data = '["foo", {"bar":["baz", null, 1.0, 2]}]'
 parse = json.loads(json_data )
print json.dumps(parse , indent=4, sort_keys=True)







Result :  
 
[
    "foo",
    {
        "bar": [
            "baz",
            null,
            1.0,
            2
        ]
    }
]

Python : Important code snippets

Important code Snippets
==============Data and Time: ==============
import datetime
print (datetime.datetime.now().day) # Result : 11
==============sorting reverse in list==============
liste=[1,5,9,2,3]
liste.sort(key=None, reverse=False)
Method2
Print(liste[::-1]
==============remove duplicates in list==============
l=[1,5,5,9,"a","b"]
liste=list(set(l))
==============Regex==============
import re
if(re.search(“.*ant.*”,”antelope”)):     #search
   print(True)
print(re.sub(r”expr”,string))              #replace
print(len(re.findall(“expr”,string))      #count
==============locals()==============
def test():
    a = 1
    b = 2
    c= 3
    return locals()
s=test()
print(s) #o/p:
(a,1) ,(b,2),(c,3),
print (type(s)) #
result : dict
==============Ranged if Condition==============
r=300
if (r in range(200,210,1)):
    print (True)
else:
    print(False)
or
if(200<r<210):
==============Validate type ==============
if isinstance(d,dict):print("hi")
if(type(d)==dict) :print(“True”)
====Higher order  functions (function name as) ====
def a():
    print("hi")
def b(func):
    func()
b(a) #
result :hi
====Higher order class (function name as) ====
class deco :   
    def func1(self):
        print ("funct1") 
    def func2(self,var):
        print(var)
              
def some_func(obj):
    obj(deco)
def some_func2(obj,var):
    obj(deco,var) 
  
some_func(deco.func1) #
O/p funct1
some_func2(deco.func2,"33") 
#O/p: 33
==============Keyword Arguments in a Function==============
def a(a=5,b): #wrong - non keyword args follow keyword ie., b should come before a
    print(a,b)
def a(b,a=5): #Correct
    print(a,b)
a(b=3,a=1)    #Result - 31
a(1,2)        #Result - 12
a(a=4,4)     #Error - non Keyword argument should come before keyword argument

=========List and tuple Arbitrary Argument in Function==============

def a(*a):
    for i in a:
        print(i)
a([1,2,3])
a((1,2,3))

Result:
[1,2,3]
(1,2,3)
==============Create sequential lists in 1 line==============
x=list(range(51,60,2))     #[51, 53, 55, 57, 59]
==============Slicing techniques==============
a=list(range(1,5))           #[1,2,3,4]
print(a[::-1])                                    #[4,3,2,1]  -reverse
print(a[::2])                   #[1,3]
print(a[::-2])                                    #[3,1]
print(a[1:-1:1])              #[2,3]
print(a[1:-1:-1])             #[]
print(a[-1:1:-1)]             #[4,3]
==============List into sublist or 1D to 2D==============
a=list(range(1,5))           #[1,2,3,4]
res=[a[i:i+2] for i in range(0,len(a),2)] #[[1,2][3,4]]
method2
m=[[i for i in range(j,j+3)] for j in range(1,7,3)]
#m = [[1, 2, 3], [4, 5, 6]]
===========Transpose a matrix using list comprehensions==============
n=[[m[i][j] for i in range(0,len(m))] for j in range(0,len(m[0]))]
Zip Matrix Transpose
n=list(zip(*m))              #list(zip(m[0],m[1])
Zip Combine 2 lists
a=[1,2,3]
b=[4,5,6]
print(list(zip(a,b)))
Combine sublists in 1 List
m = [[1, 2, 3], [4, 5, 6]]
l=m[0]+m[1]                 #l=[1,2,3,4,5,6]
List values into string
method 1 :List into string in 1 line
   l  = [1,2,3,7]
    print ("".join([str(x) for x in l] )

method 2:
    l = [1,2,3,7]
    for i in l:
        data=data+i
    print(data)

==============Type Conversions==============
s="deepak"
s=set(list(tuple(s)))
==============Dictionary (Format similar to JSON)
d={'a':'1','b':1}                     #dictionary creation
print(d.keys() , d.values() ) #['a', 'b'][2,3]),
print( 'a' in d)                        #True (list,set,tuple,str)
print(d.items())                   #'a':'1','b':1
d[“key”]=””value”              #access individual val
==============Add 2 Dictionaries==============
Res={**d1,**d2}
==============Exchange 2 variables==============
a,b=b,a
Count occurrences in a list in 1 line using re
import re
l=[1,1,2,4,4,4]
s=set(l)
res=[ len(re.findall(str(i),str(l)))  for i in s]           # [2, 1, 3]
==============Fibnocci -0,1,1,2,3,5,8…==============
res=[0,1]
for i in range(0,5,1):
    res=res+[res[-2]+res[-1]]
print(res)
==============Unit test==============
 1.”test” suffixed for unittest class.
 2. import unittest and class under test
 3. To run untitestuse:
D:\>C:\Python34\python.exe -m unittest testfile.area_test.circle_area_test

import unittest
class area():
 def circle_area(self,r):
  return(3.14*r**2)

class area_test(unittest.TestCase):
 def circle_area_test(self):
  a=area()
  self.assertAlmostEqual(a.circle_area(0),1)
  self.assertAlmostEqual(a.circle_area(0),0)
  self.assertRaises(valueError,a.circle_area(0),0)