Custom Search
Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Friday, December 6, 2019

How to Decode or Decrypt OpenStack Keystone Token

sudo python

import keystone

from keystone.token import token_formatters

formatter = token_formatters.TokenFormatter()

t = "gAAAAABd6Wl0RnnFOcy-q6aFWlr__bDcxk-GFFrLZsDh3z38Abg0iH5yFOJP7QyOVZ1SUhlIqxgID89hsZnubsM5hsbQSsYLujhU1_Zz9hlowb0chks9mogf4Pp9f1JFkr3FVQaCv2MN-ykpARLSpoV9c3m-7EFASaUNwMgysXC734598mKmWbI"

from keystone import server
server.configure()

validated_dict = formatter.validate_token(t)

validated_dict

>>> validated_dict
('a647d82c28aa4267bcf2ea99c328cd48', ['password'], [u'd6yYRIWASaKrjKTRwoGyNA'], None, None, '66cbc35f0b99430987357c2526945f8b', None, None, None, None, None, None, '2019-12-05T21:38:53.000000Z', '2019-12-05T22:38:53.000000Z')
>>> 

Tuesday, August 8, 2017

How to uninstall Python Virtualenv from IPython Jupyter Notebook

1)
List all kernelspec
$ jupyter kernelspec list
Available kernels:
  myenv1     /home/user/.local/share/jupyter/kernels/myenv1
  myenv3     /home/user/.local/share/jupyter/kernels/myenv3
  python2    /home/user/myenv3/share/jupyter/kernels/python2
  python3    /usr/local/share/jupyter/kernels/python3

2)
Uninstall  kernelspec
$ sudo ipython kernelspec uninstall myenv3


How to add Python virtualenv to IPython Jupyter notebook

1)
Install jupyter
$pip install -U jupyter

2)
Create virtual environment
$virtualenv myenv1

3)
Activate virtual environment
$source myenv1/bin/activate

4)
Install ipykernel in virtual environment
$ pip install ipykernel

5)
Add python and ipykernel in the virtual environment to jupyter notebook
$ python -m ipykernel install --user --name=myenv1

You should now be able to see your (virtualenv) kernel in the IPython
notebook menu: Kernel -> Change kernel and be able so switch to it.

Sunday, July 30, 2017

How To Set Up Jupyter Notebook for Python 3

1)
$ sudo apt-get install python3-pip python3-dev

2)
$ pip3 install -U jupyter

3)
List all installed kernelspec
$ jupyter kernelspec list

Install kernelspec for python 3
$ sudo python3 -m ipykernel install

Uninstall python 3 kernelspec
$ sudo ipython kernelspec uninstall python3

4)
$ jupyter notebook

Tuesday, May 30, 2017

How to install NumPy SciPy Matplotlib for Python 3 and Python 2.7

1)
#For Python 2.7
sudo apt-get install python-pip python-dev

sudo pip install numpy scipy matplotlib
sudo pip uninstall numpy scipy matplotlib
OR
sudo apt-get install python-numpy python-scipy python-matplotlib
sudo apt-get purge python-numpy python-scipy python-matplotlib

2)
#For python 3 and abov
e
sudo apt-get install python3-pip python3-dev

sudo pip3 install numpy scipy matplotlib
sudo pip3 uninstall numpy scipy matplotlib
OR
sudo apt-get install python3-numpy python3-scipy python3-matplotlib
sudo apt-get purge python3-numpy python3-scipy python3-matplotlib

How to install NumPy SciPy Matplotlib for Python 3 3.5 3.6

1)
sudo apt-get install python3-pip python3-dev

2)
sudo pip3 install numpy scipy matplotlib
sudo pip3 uninstall numpy scipy matplotlib
OR
sudo apt-get install python3-numpy python3-scipy python3-matplotlib
sudo apt-get purge python3-numpy python3-scipy python3-matplotlib

Monday, May 29, 2017

How to Install NumPy for Python 3.5 3.6

1)
sudo apt-get install python3-pip python3-dev

2)
Install or Uninstall numpy
sudo pip3 install numpy
sudo pip3 uninstall numpy

OR

sudo apt-get install python3-numpy
sudo apt-get purge python3-numpy


How to Install SciPy for Python 3.5 3.6

1)
sudo apt-get install python3-pip python3-dev

2)
Install/Uninstall scipy
sudo pip3 install scipy
sudo pip3 uninstall scipy

OR

sudo apt-get install python3-scipy
sudo apt-get purge python3-scipy

Monday, June 1, 2015

How to import a module installed in /usr/local/lib/python2.7/dist-packages using pip

I am using ubuntu 14.04 and can see six in following locations.

/usr/lib/python2.7/dist-packages/six.py --- 1.5.2

/usr/local/lib/python2.7/dist-packages/six.py --- 1.9.0 (installed via #sudo pip install six)

I can't import six 1.9.0 which installed via pip
#python -c "import six; print six.__version__"
1.5.2
How to import a module installed in /usr/local/lib/python2.7/dist-packages using pip

Ans:
sounds like you installed it both from the platform's package manager and with pip. I recommend not doing that. (Dont' install with pip system-wide. Install in a virtualenv or with --user.)
There is no good way. Don't install packages system-wide except through your package manager.

Solution:

* Download debian package of python-six_1.9 and install it.
#wget http://ftp.us.debian.org/debian/pool/main/s/six/python-six_1.9.0-3_all.deb
 

#sudo apt-get install gdebi
 

#sudo gdebi python-six_1.9.0-3_all.deb
 

#python -c "import six; print six.__version__"
1.9.0












Saturday, November 29, 2014

Python pip install from local cache

1)
Enable download_cache for pip.

Create a configuration file named ~/.pip/pip.conf, and add the following contents:
[global]
download_cache = ~/.cache/pip

OR

In one commeand
#printf '[global]\ndownload_cache = ~/.cache/pip\n' >> ~/.pip/pip.conf



2)
Install a package
#pip install six

* Add the package "six" to cache and install

3)
Check the files in the cache
#ls -lsh ~/.cache/pip/

4)
Install the same package again and you can see that it takes from the cache
#pip install six

* Get the package "six" from cache and install

5)
You can also manually add packages to pip cache

a)
Download the package https://pypi.python.org/packages/source/B/Babel/Babel-1.3.tar.gz#md5=5264ceb02717843cbc9ffce8e6e06bdb

b)
Copy the downloaded "Babel-1.3.tar.gz" file to "~/.cache/pip/" folder and rename ot complete url path.
#mv Babel-1.3.tar.gz https://pypi.python.org/packages/source/B/Babel/Babel-1.3.tar.gz

c)

Modify the name
Replace "/" with %2F
Repalce ":" with %3A
Like : https%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2FB%2FBabel%2FBabel-1.3.tar.gz

d)
Create another file with above name and extension ".content-type" and add the content "application/octet-stream".

Example:
#vim https%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Fm%2Fmock%2Fmock-1.0.1.tar.gz.content-type

application/octet-stream



Wednesday, November 26, 2014

Python mox mock unittest MultipleTimes example

1)
Without MultipleTimes

class Time:
    def get_time():
        pass


import mox

## Start recording (start record mode)
t=mox.MockObject(Time)

t.get_time().AndReturn("you can call me only once")


## Stop recording (start reply mode)

mox.Replay(t)

t.get_time()

t.get_time()


* Here You can call the method "get_time" only once 




2)
With MultipleTimes

class Time:
    def get_time():
        pass

import mox

t=mox.MockObject(Time)

t.get_time().MultipleTimes().AndReturn("you can call me multiple times")

mox.Replay(t)

t.get_time()

t.get_time()

* Here You can call the method "get_time" multiple times



Thursday, July 3, 2014

How to generate ER diagram of any database using python sqlalchemy_schemadisplay

1)
Install all Dependencies


#sudo pip install configparser
#sudo pip install sqlalchemy
#sudo pip install pydot
#sudo pip install sqlalchemy_schemadisplay
#sudo pip install graphviz

#sudo apt-get install GraphViz




2)
Python Script to generate ER diagram

#!/usr/bin/env python
import ConfigParser
from sqlalchemy import MetaData
from sqlalchemy_schemadisplay import create_schema_graph

config = ConfigParser.RawConfigParser()
##Open nova.conf file
config.read('/etc/nova/nova.conf')
##Read the flag "sql_connection" from nova.conf and make connection to database
connection = config.get("DEFAULT", "sql_connection")


##Or you can directly specify the connection like

##connection = "mysql://root:password@127.0.0.1/nova?charset=utf8"

##Generate graph of connected database
graph = create_schema_graph(metadata=MetaData(connection),
                 show_datatypes=False,
                 show_indexes=False,
                 rankdir='LR',
                 concentrate=False)

##Generate png image                
graph.write_png('dbschema.png')


3)
Ref:
https://coderwall.com/p/pngadg

Thursday, March 13, 2014

How to Build and Install Python Module using setuptools and Distutils

0)
Install python-setuptools
#sudo apt-get install python-setuptools

1)
http://docs.python.org/2/install/

The bulk of this document is about building and installing modules from standard source distributions.
Building and installing a module distribution using the Distutils is usually one simple command to run from a terminal.
#python setup.py install

2)
Running "python setup.py install" builds and installs all modules in one step.
You can also build everything in one step, and then install everything in a second step, by invoking the setup script twice:
#python setup.py build
#python setup.py install


3)
How building works
-------------------

The "build" command is responsible for putting the files to install into a build directory.
By default, this is "build" under the distribution root.

The default layout for the build tree is as follows:

--- build/ --- lib/
or
--- build/ --- lib./
               temp.
/

4)
How installation works
-----------------------

The work of the install command is relatively simple: all it has to do is copy everything under "build/lib" (or build/lib.plat) to your chosen installation directory.
If you don’t choose an installation directory—i.e., if you just run "python setup.py install" then the install command installs to the standard location for third-party Python modules. This location varies by platform and by how you built/installed Python itself

5)
Alternate installation: the user scheme
----------------------------------------

This scheme is designed to be the most convenient solution for users that don’t have write permission to the global site-packages directory or don’t want to install into it. It is enabled with a simple option:

#python setup.py install --user

Files will be installed into subdirectories of "site.USER_BASE" (Default value is ~/.local for UNIX).
This scheme installs pure Python modules and extension modules in the same location


http://docs.python.org/2/library/site.html#site.USER_BASE

6)
Custom Installation
--------------------

To create a custom installation scheme, you start with one of the alternate schemes and override some of the installation directories used for the various types of files.
Specifying the entire installation scheme every time you install a new module distribution would be very tedious. Thus, you can put these options into your Distutils config file

7)
Distutils Configuration Files
------------------------------

You can use Distutils configuration files to record personal or site preferences for any Distutils options. That is, any option to any command can be stored in one of two or three (depending on your platform) configuration files, which will be consulted before the command-line is parsed. This means that configuration files will override default values, and the command-line will in turn override configuration files. Furthermore, if multiple configuration files apply, values from “earlier” files are overridden by “later” files.

8)
Location and names of config files
-----------------------------------

Type of file : Location and filename
system : prefix/lib/pythonver/distutils/distutils.cfg
personal : $HOME/.pydistutils.cfg
local : setup.cfg <====


9)
Syntax of config files
-----------------------

The Distutils configuration files all have the same syntax. The config files are grouped into sections. There is one section for each 'Distutils command', plus a "global" section for global options that affect every command. Each section consists of one option per line, specified as "option=value".
And if it is used as the "setup.cfg" for a particular module distribution, it affects only that distribution.

10)
Writing the Setup Configuration File
-------------------------------------

http://docs.python.org/2/distutils/configfile.html

a)
Configuration files also let you provide default values for any command option, which the installer can then override either on the command-line or by editing the config file.

 In fact, "setup.cfg" are processed after the contents of the setup script, but before the command-line. This has several useful consequences:

* installers can override some of what you put in setup.py by editing setup.cfg
* you can provide non-standard defaults for options that are not easily set in setup.py
* installers can override anything in setup.cfg using the command-line options to setup.py

b)
The basic syntax of the configuration file is simple:

[command]
option=value
...


where command is one of the Distutils commands (e.g. build_py, install), and option is one of the options that command supports. Any number of options can be supplied for each command, and any number of command sections can be included in the file.

You can find out the list of options supported by a particular command with the universal --help option, e.g.
#python setup.py --help build_ext

11)
Tips for Configuration File
----------------------------

a)
Some configuration file sections
Some "python setup.py" commands
* metadata
* global
* files
* build_sphinx
* nosetests

b)
* Run "python setup.py --help-commands" to see all commands.
* Run "python setup.py cmd --help" to see all options of a command.
Example:
#python setup.py build_sphinx --help
#python setup.py nosetests --help


c)
https://github.com/openstack/nova/blob/master/setup.cfg
https://github.com/openstack/nova/blob/master/setup.py

https://github.com/openstack/horizon/blob/master/setup.cfg
https://github.com/openstack/horizon/blob/master/setup.py

https://github.com/openstack/cinder/blob/master/setup.cfg
https://github.com/openstack/cinder/blob/master/setup.py

https://github.com/openstack/glance/blob/master/setup.cfg
https://github.com/openstack/glance/blob/master/setup.py

https://github.com/openstack/swift/blob/master/setup.cfg
https://github.com/openstack/swift/blob/master/setup.py

12)
Getting Started With setuptools and setup.py
---------------------------------------------

a)
https://pythonhosted.org/an_example_pypi_project/setuptools.html
http://pythonhosted.org/setuptools/setuptools.html

b)
Example setup.py
import setuptools
setuptools.setup(setup_requires=['pbr'], pbr=True)


http://docs.openstack.org/developer/pbr/

pbr is a library for managing setuptools packaging needs in a consistent manner.pbr reads and then filters the setup.cfg data through a setup hook to fill in default values and provide more sensible behaviors, and then feeds the results in as the arguments to a call to setup.py - so the heavy lifting of handling python packaging needs is still being done by setuptools.

13)
manifest template, called MANIFEST.in
-----------------------------------------------------
http://docs.python.org/2/distutils/sourcedist.html

a)
The manifest template is just a list of instructions for how to generate your manifest file, MANIFEST, which is the exact list of files to include in your source distribution. The sdist command processes this template and generates a manifest based on its instructions and what it finds in the filesystem.

b)
MANIFEST.in tells Distutils what files to include in the source distribution but it does not directly affect what files are installed. For that you need to include the appropriate files in the setup.py file, generally either as package data or as additional files.


Tuesday, March 4, 2014

How To Deploy a Python Flask Application with apache and mod_wsgi

0)
Install apache and mode_wsgi
=========================
#sudo apt-get install apache2
#sudo apt-get install libapache2-mod-wsgi




1)
Clone the project
==================

#cd /usr/share
#sudo git clone https://github.com/sajuptpm/reg-service.git openstack_horizon_reg_service
#cd openstack_horizon_reg_service


2)
Create Virtualenv
====================

#sudo virtualenv venv
#source venv/bin/activate
#sudo pip install -r requirements.txt


3)
Create wsgi file
==================

#sudo mkdir wsgi
#cd wsgi
#sudo vim flask.wsgi
import os
import sys


##Virtualenv Settings
activate_this = '/usr/share/openstack_horizon_reg_service/venv/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))


##Replace the standard out
sys.stdout = sys.stderr

##Add this file path to sys.path in order to import settings
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '../..'))

##Add this file path to sys.path in order to import app
sys.path.append('/usr/share/openstack_horizon_reg_service/')

##Create appilcation for our app
from openstack_horizon_reg_service.run import app as application

4)
Apache Settings
=================

#cd /etc/apache2/conf-enabled
#sudo vim openstack-horizon-reg-service.conf 

WSGIScriptAlias /horizonreg /usr/share/openstack_horizon_reg_service/wsgi/flask.wsgi
WSGIScriptReloading On
 

Directory /usr/share/openstack_horizon_reg_service/wsgi>
  Order allow,deny
  Allow from all
Directory>

4a)
vim /etc/apache2/apache2.conf
#Include generic snippets of statements.
#Following line should be there
IncludeOptional conf-enabled/*.conf

5)
Restart apache
===============

#sudo service apache2 restart

6)
http://127.0.0.1/horizonreg/users/123

Monday, February 17, 2014

How to install python packages in virtualenv using sudo

How to install python packages in virtualenv using sudo

Issue
=====

a)
I created a virtualenv ".venv" using following command in /opt
#cd /opt
#sudo virtualenv .venv
#source .venv/bin/activate
#sudo easy_install python-keystoneclient

But package not installing in virtualenv ".venv" instead it pointing to
/usr/local/lib/python2.7/dist-packages/python_keystoneclient-0.6.0.2.g43f8870-py2.7.egg

b)
(.venv2)saju@rildemo2:/opt/horizon_reg_service$ sudo easy_install python-keystoneclient
Searching for python-keystoneclient
Best match: python-keystoneclient 0.6.0.2.g43f8870
Processing python_keystoneclient-0.6.0.2.g43f8870-py2.7.egg
python-keystoneclient 0.6.0.2.g43f8870 is already the active version in easy-install.pth
Installing keystone script to /usr/local/bin

Using /usr/local/lib/python2.7/dist-packages/python_keystoneclient-0.6.0.2.g43f8870-py2.7.egg
Processing dependencies for python-keystoneclient
Finished processing dependencies for python-keystoneclient
(.venv2)saju@rildemo2:/opt/horizon_reg_service$

Solutions
==========

1) (Tested and working)
sudo is probably screwing with $PATH. delete the virtualenv, `sudo -i` to get a root shell, then make the virtualenv without sudo (as root)
#sudo -i
#cd /opt
#virtualenv .venv
#source .venv/bin/activate
#pip install python-keystoneclient


2)
the better thing to do would be to make the /opt/.venv folder, change the ownership to your user, and then do the virtualenv stuff as your normal user (without sudo)

Sunday, December 29, 2013

Python Selenium Example

"""
#pip install selenium
#pip install BeautifulSoup
#pip install pyvirtualdisplay
#sudo apt-get install xvfb



"""

"""

Driver
=======

>>> dir(d)
['NATIVE_EVENTS_ALLOWED', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_is_remote', '_unwrap_value', '_wrap_value', 'add_cookie', 'application_cache', 'back', 'binary', 'capabilities', 'close', 'command_executor', 'create_web_element', 'current_url', 'current_window_handle', 'delete_all_cookies', 'delete_cookie', 'desired_capabilities', 'error_handler', 'execute', 'execute_async_script', 'execute_script', 'find_element', 'find_element_by_class_name', 'find_element_by_css_selector', 'find_element_by_id', 'find_element_by_link_text', 'find_element_by_name', 'find_element_by_partial_link_text', 'find_element_by_tag_name', 'find_element_by_xpath', 'find_elements', 'find_elements_by_class_name', 'find_elements_by_css_selector', 'find_elements_by_id', 'find_elements_by_link_text', 'find_elements_by_name', 'find_elements_by_partial_link_text', 'find_elements_by_tag_name', 'find_elements_by_xpath', 'firefox_profile', 'forward', 'get', 'get_cookie', 'get_cookies', 'get_screenshot_as_base64', 'get_screenshot_as_file', 'get_window_position', 'get_window_size', 'implicitly_wait', 'is_online', 'maximize_window', 'name', 'orientation', 'page_source', 'profile', 'quit', 'refresh', 'save_screenshot', 'session_id', 'set_page_load_timeout', 'set_script_timeout', 'set_window_position', 'set_window_size', 'start_client', 'start_session', 'stop_client', 'switch_to_active_element', 'switch_to_alert', 'switch_to_default_content', 'switch_to_frame', 'switch_to_window', 'title', 'window_handles']
>>>

Element
=======

['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_execute', '_id', '_parent', '_upload', 'clear', 'click', 'find_element', 'find_element_by_class_name', 'find_element_by_css_selector', 'find_element_by_id', 'find_element_by_link_text', 'find_element_by_name', 'find_element_by_partial_link_text', 'find_element_by_tag_name', 'find_element_by_xpath', 'find_elements', 'find_elements_by_class_name', 'find_elements_by_css_selector', 'find_elements_by_id', 'find_elements_by_link_text', 'find_elements_by_name', 'find_elements_by_partial_link_text', 'find_elements_by_tag_name', 'find_elements_by_xpath', 'get_attribute', 'id', 'is_displayed', 'is_enabled', 'is_selected', 'location', 'location_once_scrolled_into_view', 'parent', 'send_keys', 'size', 'submit', 'tag_name', 'text', 'value_of_css_property']


"""



import selenium
from selenium import webdriver
from selenium import selenium as sel
import time
from selenium.webdriver.support.ui import WebDriverWait
import BeautifulSoup
from pyvirtualdisplay import Display
import sys

from PIL import Image
from urllib import urlretrieve

import logging
LOGGER = logging.getLogger('selenium')
hdlr = logging.FileHandler('./selenium.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
LOGGER.addHandler(hdlr)
LOGGER.setLevel(logging.INFO)


class MeetMe:
    """
    """
    TARGET_URL = "http://www.blabla.com"
    DUMP_FILE = "response.html"
    CAPTCHA_FILE_NAME = "captcha.jpeg"

    def __init__(self):
        """
        """
        self.display = Display(visible=0, size=(1200,1600))
        self.display.start()
        self.url = self.TARGET_URL
        self.driver  = webdriver.Firefox()
        self.retry = 0
        LOGGER.info("\n-------------start---------------\n")
   
    def __del__(self):
        """
        """
        print "====closing browser=="
        self.close_browser()

    def open_url(self, url):
        """
        """
        self.driver.get(url)

    def find_element_by_name(self, name):
        """
        """
        return self.driver.find_element_by_name(name)

    def find_element_by_id(self, id):
        """
        """
        return self.driver.find_element_by_id(id)
   
    def close_browser(self):
        """
        """
        self.driver.close()


    def dump_response_to_file(self, filename=None):
        """
        """
        if not filename:
            filename = self.DUMP_FILE
        html = self.driver.page_source
        soup_res = BeautifulSoup.BeautifulSoup(html)
        with open(filename, 'w') as fp:
            fp.write(str(soup_res))

    def execute_script(self, script):
        """
        self.driver.execute_script("document.getElementsByName('body')[0].setAttribute('type', 'text');")
        """
        self.driver.execute_script(script)

    def save_screenshot(self, filename):
        """
        """
        self.driver.save_screenshot(filename)

    def select_checkbox(self, element, select=True):
        """
        """
        if select:
            if not element.is_selected():
                element.click()
        else:
            if element.is_selected():
                element.click()

    def get_file(self, link, filename="test.tif"):
        ##Download and save file with name filename
        urlretrieve(link, filename)

    def show_image(self, image_name):
        """
        """
        im = Image.open(image_name)
        im.show()

"""
signup_frm_elements_id = {
            #"quicksignupFrm":"quicksignupFrm",##

            "firstname":"firstname",##:text
            "lastname":"lastname",##:text
            "email":"email",##:text
            "password":"password",##:password
            #"location":"location",##

            #"regionHidden":"regionHidden",##:hidden
            #"country":"country",##:text:hidden
            "gender":"gender",##:
            "day":"day",##:
            "terms":"terms",##:checkbox
            #"halRecaptchaContainer":"halRecaptchaContainer",##

            #"dynamicRecaptcha":"dynamicRecaptcha",##

            #"recaptcha_image":"recaptcha_image",##

            #"signupButton":"signupButton",##


"""
### CAPCHA ###

   


"""
recaptcha_image_element = me.find_element_by_id("recaptcha_image")
if recaptcha_image_element:
    ##Get child tag "img" of tag "recaptcha_image"
    recaptcha_img_tag = recaptcha_image_element.find_element_by_tag_name("img")
    if recaptcha_img_tag:
        ##Get url of captcha image
        recaptcha_img_src = recaptcha_img_tag.get_attribute("src")
        print "===recaptcha_img_src===", recaptcha_img_src
        me.get_file(recaptcha_img_src, filename=me.CAPTCHA_FILE_NAME)
        me.show_image(me.CAPTCHA_FILE_NAME)
        captcha_chars = raw_input("Enter Captcha:")
        recaptcha_text_field = me.find_element_by_id("recaptcha_response_field")
        recaptcha_text_field.send_keys(captcha_chars)

me.save_screenshot("k3")
me.dump_response_to_file("signuotest1.html")
me.save_screenshot("k4")




























Friday, November 22, 2013

Python Django How to send email from python console

0)
First setup and configure email server (exim)

1)
Activate virtualenv

2)
Got you django project folder and run following command
#export DJANGO_SETTINGS_MODULE=myproject.settings



3)
Open python terminal and run following command
#python
import myproject.settings as setting


setting.EMAIL_HOST
setting.EMAIL_PORT
 

from django.core.mail import send_mail
 

send_mail('Subject here2', 'Here is the message1.', 'from@mymailserver.com', ['sajuptpm@gmail.com'], fail_silently=False)

Tuesday, November 19, 2013

How to serve an app using python paste

How to serve an app using python paste
###############################


1)
* config.ini

[app:main]
paste.app_factory = service_app:app_factory


2)
* deploy.py

from paste import httpserver
from paste.deploy import loadapp
app = loadapp('config:config.ini', relative_to='.')
httpserver.serve(app, host='127.0.0.1', port='8080')


3)
* service_app.py

def application(environ, start_response):
    """Simple WSGI application"""
    response_headers = [('Content-type','text/plain')]
    status = '200 OK'
    start_response(status, response_headers)
    if environ['PATH_INFO'] == '/login':
    #http://pythonpaste.org/modules/recursive.html
        return ["login page"]
    else:
        return ['Hello world']

def app_factory(global_config, **local_config):
    """This function wraps our simple WSGI app so it
    can be used with paste.deploy"""
    return application

4)
How to run

#python deploy.py
serving on http://127.0.0.1:8080

5)
goto the urls

http://127.0.0.1:8080
http://127.0.0.1:8080/login

Wednesday, November 6, 2013

Python Django Configure Exim Mail Server

1)Install Exim
#apt-get update
#apt-get upgrade
#apt-get install exim4-daemon-light mailutils



2)Configure Exim
#dpkg-reconfigure exim4-config

3)
Settings.py Changes
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25