Python‎ > ‎keywords‎ > ‎

import


Definition
Importing module is required in the Shell window and the Editor window.

Syntax
import (module name)
  • import fractions
  • from fractions import Fraction
  • import decimal
  • from decimal import Decimal
  • import operators
  • import math
  • import random
  • import webbrowser
  • import tkinter
  • import turtle
  • import requests
EXAMPLE
Here, in this examples, the form validation is processed through the calling the function in the forms.EmailField(). The  function validated the list items after the form is submitted through POST method.
 Steps for creating virtual environment, startproject, startapps, & running server:
  • virtualenv myenv
  • cd  myenv
  • .\Scripts\activate
  • .\Scripts\deactivate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py runserver

Files


setting.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles', 'myapp', 
)

urls.py

from myapp.views import submit

urlpatterns = [
    url(r'^', submit),
]

myapp/forms.py

from django import forms
from django.core.exceptions import ValidationError

def Validate(email):
    list=['adil@adilwaseem.com', 'adil@pythonlake.com','contact@adilwaseem.com']
    if email not in list:
        raise ValidationError("%s is not in our record."% email )

class AccessForm(forms.Form):
    email=forms.EmailField(label='Email',validators=[Validate])

myapp/views.py

from django.shortcuts import render

from .forms import AccessForm

def submit(request):
    if request.method == 'POST':
        form=AccessForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    else:
        form = AccessForm()

    return render(request, 'myapp\index.html', {'form':form})

myapp/index.html

<!DOCTYPE html>
<html>
<title> </title>
<body>

<form action="/Response/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

</body>
</html>

view at localhost:8000/








Example
The django web framework returns with hyperlink created through html5 integrated with django Scripts.
Steps for creating virtual environment, startproject, startapps, migration, & running server:
    • virtualenv string
    • cd  string
    • .\Scripts\activate
    • pip install django
    • python .\Scripts\django-admin.py startproject str
    • cd str
    • python manage.py runserver
    • key ctr c to break the server
    • python manage.py startapp htmlapp
    • python manage.py runserver

    File structure 




    settings.py

    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles','htmlapp',
    )

    urls.py

    from django.conf.urls import url, patterns
    from htmlapp.views import html_links

    urlpatterns = patterns('',

        url(r'^html_links/', html_links),
        )

    httpapp/views.py


    def html_links(request):
        link='<div style="background-color:pink; color:white; padding:20px;">'\
             '<a href="http://www.pythonlake.com/">Python Lake</a> <hr>' \
             '<a href="http://www.pythonlake.com/python/django">Django</a> <hr> ' \
             '<a href="http://www.pythonlake.com/python/django/djangohttp">django.http</a> <hr> ' \
             '<a href="http://www.pythonlake.com/python/django/djangohttp/httpresponse">HttpResponse</a> <hr> ' \
             '</div>'
        return HttpResponse(link)


    Running the server through Window CMD command.







    The django web framework is used to create the application which convert the string into uppercase using str.upper method. The string_method_upper.py calls the string_method.views.py file to render the function.
    Windows CMD commands for creating virtualenv, startproject, startapp, and running server.
    • virtualenv string
    • cd string
    • .\Scripts\activate
    • pip install django
    • python .\Scripts\django-admin.py startproject str
    • cd str
    • python manage.py runserver
    • python manage.py startapp string_methods
    • python manage.py startapp string_method_upper
    • python manage.py runserver



    string_method_upper/views.py


    def string_method_upper (request):
        return string_upper(request)

    string_methods/views.py


    def string_upper(request):
        return HttpResponse("Python is a simple, powerful and high-level programming language "
                            "and the logic and structure is consistent with the way we "
                            "reasons. ".upper())


    urls.py

    from string_methods.views import*
    from string_method_upper.views import *

    urlpatterns=patterns('', url(r'^string_method_upper/', string_method_upper),)

    settings.py

    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles','string_methods', 'string_method_upper',
    )




    Example
    The for loop returns the headers values.
     >>> import requests
    >>> r=requests.get('http://www.pythonlake.com/aboutus')
    >>> for s in r.headers:
    ...     print(s)
    ... 
    x-xss-protection
    transfer-encoding
    x-content-type-options
    vary
    expires
    content-type
    server
    date
    cache-control
    accept-ranges
    last-modified
    x-robots-tag
    alternate-protocol

    The request request is subject to the exception of ConnectionError in finding the turtle parameters in the www.pythonlake.com homepage.
    >>> import requests
     >>> try:
    ...     r=requests.get('http://www.pythonlake.com',params='www.pythonlake.com')
    ...     t=r.text
    ...     t.find('turtle')
    ... except:
    ...     print(e)
    ...     
    103986
    >>> 


    The code gets http library of  www.pythonlake.com and store in the variable r and str.count method is used to count the strings.
    >>> import requests
    >>> r=requests.get('http://www.pythonlake.com')
    >>> t=r.text
    >>> t.count('www.pythonlake.com')
    721 

    Import math
    The lambda returns with equation computation.
    import math
    x=[math.log(2,10),math.log10(22), math.log2(2)]
    y=[math.trunc(2.1)]
    if sum(map(lambda a,b: a+b/2, x,y)).__le__(y):
        print("The return is large or equal to 2.0")
    else:
        print("The value does not meet the criteria")

    >>> 
    The return is large or equal to 2.0
    >>>

    from decimal from*
    The method returns with the minimum value in the sets equation set1/set2*set2 is greater than 2. 
    from decimal import*
    set1={Decimal(-1355).adjusted(),Decimal(-233.321).copy_negate(), Decimal(-23.99).exp()}
    set2={ Decimal(2.0).fma(3,7),Decimal(1.1).log10()}
    if min(map(lambda a,b: a/b*b, set1, set2)).__gt__(2):
            print("Return is greater than 2.")
    else:
            print("Not within parameters")

    >>> 
    Return is greater than 2.
    >>>       


    import random
    Return with round value of random.betavariate()+(random.gammavariate().
    import random
    x=round((random.betavariate(3,1))+(random.gammavariate(3,21)))
    if x in range(1,9):
        print("The random value is single digit: ", x)
        y=input("Do you add to generate number one more time: y/n")
        if y=="y":
            print("Second random value is: ", round((random.betavariate(3,1))+(random.gammavariate(3,21))))
                elif y=="n":
                    next
    elif x in (range(10,99)):
        print("Random value is: ", round((random.betavariate(3,1))+(random.gammavariate(3,21))))
        z=input("Do you add to generate number one more time: y/n: ")
        if z=="y":
            print("Second random value is: ", round((random.betavariate(3,1))+(random.gammavariate(3,21))))
        elif z=="n":
            next
    else:
    print("Random value is: ", round((random.betavariate(3,1))+(random.gammavariate(3,21))))

    import(from decimal import Decimal)
    The method return decimal values in various decimal methods through input() method.
    from decimal import Decimal

    print("Python Decimal Methods")
    a=Decimal(input("Enter Decimal Value: "))

    print("Your value in Decimal().adjusted()) method is: ", Decimal(a).adjusted())

    print("---------------------------------------------------------------------------------")
    print("While other methods return your value as: ")
    print("Your value in Decimal().as_tuple(() method is: ", Decimal(a).as_tuple())

    print("---------------------------------------------------------------------------------")
    print("Your value in Decimal().canonical() method is: ", Decimal(a).canonical())

    print("---------------------------------------------------------------------------------")
    print("Your value in Decimal().compare(your value-1) method is: ", Decimal(a).compare(a-1))

    print("---------------------------------------------------------------------------------")
    print("Your value in Decimal().compare_signal(3)) method is: ", Decimal(a).compare_signal(3))

    >>> 
    Python Decimal Methods
    Enter Decimal Value: 55
    Your value in Decimal().adjusted()) method is: 1
    ---------------------------------------------------------------------------------
    While other methods return your value as: 
    Your value in Decimal().as_tuple(() method is: DecimalTuple(sign=0, digits=(5, 5), exponent=0)
    ---------------------------------------------------------------------------------
    Your value in Decimal().canonical() method is: 55
    ---------------------------------------------------------------------------------
    Your value in Decimal().compare(your value-1) method is: 1
    ---------------------------------------------------------------------------------
    Your value in Decimal().compare_signal(3)) method is: 1
    >>>


    The method return with the difference in the set items:
    Here is how Error method printed the error message.
     import webbrowser

    x=input("Please enter web dress:")

    if x.__eq__('www.pythonlake.com'):
        webbrowser.open(x)

        webbrowser.Error("Not allowed to access the file")

    >>> 
    Please enter web dress:www.amazon.com
    Not allowed to access the file
    >>> 


    import tkinter
    There simple mainloop widget(). 
    import tkinter
    class maintloop1():
        def __init__(self,a):
            self.a=a
            a.mainloop()

    x=tkinter.Tk()
    maintloop1(x)





    Graphics is created through for loop within for loop through random.sample() color selection.
    import random

    turtle.screensize(400,400)
    turtle.speed(10)
    turtle.pensize(1)
    turtle.bgcolor("black")
        
    color_list= ['snow', 'ghostwhite', 'whitesmoke', 'gainsboro', 'floralwhite', 'oldlace',
        'linen', 'antiquewhite', 'papayawhip', 'blanchedalmond', 'bisque', 'peachpuff',
        'navajowhite', 'lemonchiffon', 'mintcream', 'azure', 'aliceblue', 'lavender',
        'lavenderblush', 'mistyrose', 'darkslategray', 'dimgray', 'slategray',
        'lightslategray', 'gray', 'lightgrey', 'midnightblue', 'navy', 'cornflowerblue', 'darkslateblue',
        'slateblue', 'mediumslateblue', 'lightslateblue', 'mediumblue', 'royalblue',  'blue',
        'dodgerblue', 'deepskyblue', 'skyblue', 'lightskyblue', 'steelblue', 'lightsteelblue',
        'lightblue', 'powderblue', 'paleturquoise', 'darkturquoise', 'mediumturquoise', 'turquoise',
        'cyan', 'lightcyan', 'cadetblue', 'mediumaquamarine', 'aquamarine', 'darkgreen', 'darkolivegreen',
        'darkseagreen', 'seagreen', 'mediumseagreen', 'lightseagreen', 'palegreen', 'springgreen',
        'lawngreen', 'mediumspringgreen', 'greenyellow', 'limegreen', 'yellowgreen',
        'forestgreen', 'olivedrab', 'darkkhaki', 'khaki', 'palegoldenrod', 'lightgoldenrodyellow',
        'lightyellow', 'yellow', 'gold', 'lightgoldenrod', 'goldenrod', 'darkgoldenrod', 'rosybrown',
        'indianred', 'saddlebrown', 'sandybrown',
        'darksalmon', 'salmon', 'lightsalmon', 'orange', 'darkorange',
        'coral', 'lightcoral', 'tomato', 'orangered', 'red', 'hotpink', 'deeppink', 'pink', 'lightpink',
        'palevioletred', 'maroon', 'mediumvioletred', 'violetred',
        'mediumorchid', 'darkorchid', 'darkviolet', 'blueviolet', 'purple', 'mediumpurple',
        'thistle', 'snow2', 'snow3',
        'snow4', 'seashell2', 'seashell3', 'seashell4', 'AntiqueWhite1', 'AntiqueWhite2',
        'AntiqueWhite3', 'AntiqueWhite4', 'bisque2', 'bisque3', 'bisque4', 'PeachPuff2',
        'PeachPuff3', 'PeachPuff4', 'NavajoWhite2', 'NavajoWhite3', 'NavajoWhite4',
        'LemonChiffon2', 'LemonChiffon3', 'LemonChiffon4', 'cornsilk2', 'cornsilk3',
        'cornsilk4', 'ivory2', 'ivory3', 'ivory4', 'honeydew2', 'honeydew3', 'honeydew4',
        'LavenderBlush2', 'LavenderBlush3', 'LavenderBlush4', 'MistyRose2', 'MistyRose3',
        'MistyRose4', 'azure2', 'azure3', 'azure4', 'SlateBlue1', 'SlateBlue2', 'SlateBlue3',
        'SlateBlue4', 'RoyalBlue1', 'RoyalBlue2', 'RoyalBlue3', 'RoyalBlue4', 'blue2', 'blue4',
        'DodgerBlue2', 'DodgerBlue3', 'DodgerBlue4', 'SteelBlue1', 'SteelBlue2',
        'SteelBlue3', 'SteelBlue4', 'DeepSkyBlue2', 'DeepSkyBlue3', 'DeepSkyBlue4',
        'SkyBlue1', 'SkyBlue2', 'SkyBlue3', 'SkyBlue4', 'LightSkyBlue1', 'LightSkyBlue2',
        'LightSkyBlue3', 'LightSkyBlue4', 'SlateGray1', 'SlateGray2', 'SlateGray3',
        'SlateGray4', 'LightSteelBlue1', 'LightSteelBlue2', 'LightSteelBlue3',
        'LightSteelBlue4', 'LightBlue1', 'LightBlue2', 'LightBlue3', 'LightBlue4',
        'LightCyan2', 'LightCyan3', 'LightCyan4', 'PaleTurquoise1', 'PaleTurquoise2',
        'PaleTurquoise3', 'PaleTurquoise4', 'CadetBlue1', 'CadetBlue2', 'CadetBlue3',
        'CadetBlue4', 'turquoise1', 'turquoise2', 'turquoise3', 'turquoise4', 'cyan2', 'cyan3',
        'cyan4', 'DarkSlateGray1', 'DarkSlateGray2', 'DarkSlateGray3', 'DarkSlateGray4',
        'aquamarine2', 'aquamarine4', 'DarkSeaGreen1', 'DarkSeaGreen2', 'DarkSeaGreen3',
        'DarkSeaGreen4', 'SeaGreen1', 'SeaGreen2', 'SeaGreen3', 'PaleGreen1', 'PaleGreen2',
        'PaleGreen3', 'PaleGreen4', 'SpringGreen2', 'SpringGreen3', 'SpringGreen4',
        'green2', 'green3', 'green4', 'chartreuse2', 'chartreuse3', 'chartreuse4',
        'OliveDrab1', 'OliveDrab2', 'OliveDrab4', 'DarkOliveGreen1', 'DarkOliveGreen2',
        'DarkOliveGreen3', 'DarkOliveGreen4', 'khaki1', 'khaki2', 'khaki3', 'khaki4',
        'LightGoldenrod1', 'LightGoldenrod2', 'LightGoldenrod3', 'LightGoldenrod4',
        'LightYellow2', 'LightYellow3', 'LightYellow4', 'yellow2', 'yellow3', 'yellow4',
        'gold2', 'gold3', 'gold4', 'goldenrod1', 'goldenrod2', 'goldenrod3', 'goldenrod4',
        'DarkGoldenrod1', 'DarkGoldenrod2', 'DarkGoldenrod3', 'DarkGoldenrod4',
        'RosyBrown1', 'RosyBrown2', 'RosyBrown3', 'RosyBrown4', 'IndianRed1', 'IndianRed2',
        'IndianRed3', 'IndianRed4', 'sienna1', 'sienna2', 'sienna3', 'sienna4', 'burlywood1',
        'burlywood2', 'burlywood3', 'burlywood4', 'wheat1', 'wheat2', 'wheat3', 'wheat4', 'tan1',
        'tan2', 'tan4', 'chocolate1', 'chocolate2', 'chocolate3', 'firebrick1', 'firebrick2',
        'firebrick3', 'firebrick4', 'brown1', 'brown2', 'brown3', 'brown4', 'salmon1', 'salmon2',
        'salmon3', 'salmon4', 'LightSalmon2', 'LightSalmon3', 'LightSalmon4', 'orange2',
        'orange3', 'orange4', 'DarkOrange1', 'DarkOrange2', 'DarkOrange3', 'DarkOrange4',
        'coral1', 'coral2', 'coral3', 'coral4', 'tomato2', 'tomato3', 'tomato4', 'OrangeRed2',
        'OrangeRed3', 'OrangeRed4', 'red2', 'red3', 'red4', 'DeepPink2', 'DeepPink3', 'DeepPink4',
        'HotPink1', 'HotPink2', 'HotPink3', 'HotPink4', 'pink1', 'pink2', 'pink3', 'pink4',
        'LightPink1', 'LightPink2', 'LightPink3', 'LightPink4', 'PaleVioletRed1',
        'PaleVioletRed2', 'PaleVioletRed3', 'PaleVioletRed4', 'maroon1', 'maroon2',
        'maroon3', 'maroon4', 'VioletRed1', 'VioletRed2', 'VioletRed3', 'VioletRed4',
        'magenta2', 'magenta3', 'magenta4', 'orchid1', 'orchid2', 'orchid3', 'orchid4', 'plum1',
        'plum2', 'plum3', 'plum4', 'MediumOrchid1', 'MediumOrchid2', 'MediumOrchid3',
        'MediumOrchid4', 'DarkOrchid1', 'DarkOrchid2', 'DarkOrchid3', 'DarkOrchid4',
        'purple1', 'purple2', 'purple3', 'purple4', 'MediumPurple1', 'MediumPurple2',
        'MediumPurple3', 'MediumPurple4', 'thistle1', 'thistle2', 'thistle3', 'thistle4',
        'gray1', 'gray2', 'gray3', 'gray4', 'gray5', 'gray6', 'gray7', 'gray8', 'gray9', 'gray10',
        'gray11', 'gray12', 'gray13', 'gray14', 'gray15', 'gray16', 'gray17', 'gray18', 'gray19',
        'gray20', 'gray21', 'gray22', 'gray23', 'gray24', 'gray25', 'gray26', 'gray27', 'gray28',
        'gray29', 'gray30', 'gray31', 'gray32', 'gray33', 'gray34', 'gray35', 'gray36', 'gray37',
        'gray38', 'gray39', 'gray40', 'gray42', 'gray43', 'gray44', 'gray45', 'gray46', 'gray47',
        'gray48', 'gray49', 'gray50', 'gray51', 'gray52', 'gray53', 'gray54', 'gray55', 'gray56',
        'gray57', 'gray58', 'gray59', 'gray60', 'gray61', 'gray62', 'gray63', 'gray64', 'gray65',
        'gray66', 'gray67', 'gray68', 'gray69', 'gray70', 'gray71', 'gray72', 'gray73', 'gray74',
        'gray75', 'gray76', 'gray77', 'gray78', 'gray79', 'gray80', 'gray81', 'gray82', 'gray83',
        'gray84', 'gray85', 'gray86', 'gray87', 'gray88', 'gray89', 'gray90', 'gray91', 'gray92',
        'gray93', 'gray94', 'gray95', 'gray97', 'gray98', 'gray99']

    for m in range(0,200):
        turtle.pendown()
        colors=random.sample(color_list,1)
        turtle.color(colors)
        turtle.forward(m)
        
        for m1 in range(0,20):
            turtle.right(45+m1)
            turtle.color(colors)
            turtle.forward(1+m+m1)

    turtle.hideturtle()






     The tensorflow run the String.
    import tensorflow as tf
    c = tf.constant('Python Lake')

    Tensor("Const:0", shape=(), dtype=string) 

    Comments