Monday, March 18, 2013

Creating Python Virtual Environment Without Installing To The System

When you develop projects in python, you often met the situation where you will need to install various packages that will clutter the general python installation in your system. Usually people will use the famous virtualenv. However, it often brings trouble when you have to run 2 or more python environments simultaneously.

I'm about to share a simple trick that you can use to separate those environment, still using virtualenv but we're using it differently. The examples are in unix/linux, but the usage is quite similar in windows.

First, download virtualenv.py from https://raw.github.com/pypa/virtualenv/master/virtualenv.py.
That should be done in seconds.

Next up, create any folder where ever you want to create the virtual environment and copy the downloaded virtualenv.py  file inside the folder.

Now, run the following command:
python virtualenv.py env
That will create a folder called env inside your current folder and the folder will contain your newly created virtual environment.

Installing package into the environment? Worry not, it's very simple.

simply run:
env/bin/pip install
after installting the packages, write your python applications inside the folder. When you want to run the file, you have 2 ways of doing it:


First, the fast way but a bit longer typing:
simply run:
env/bin/python .py
Second, longer at first but takes less time if you have to repeat it on and on.
Add the following line in the topmost line of your file
#! env/bin/python
then run

chmod a+x .py

afterwards to run it, you can simply call it this way:
./.py
Aaaaand you're done! No need to change stop virtual environments to run the other and your global system is clutter free.

In windows, change the env/bin/pip or env/bin/python into env/Scripts/pip or env/Scripts/python.

Hope that helps.

Happy hacking!!!

regards

-E-


follow @femmerling on twitter

Thursday, March 7, 2013

LDAP Login Authentication Using Python LDAP

About 2 days ago, I have to create an app for internal company use. I'm using EmeraldBox to develop it. At first I created the user model to save user credentials and using it during the login process.

However, the boss came with an idea that I should use LDAP login since we have it and it provides a single sign-on solution, which is better.

So, I googled around and found python-ldap.

You can easily install it by running:
pip install python-ldap
and it's ready to use.

The question is, how can I use it?

Check out the code I use below for references. The steps should be the same. However, you need to adjust some values accordingly to the LDAP settings in the server.

It's as easy as that and you can perform login and get the user credentials. In my app, I use Flask's session to put the user credentials so I can fetch it whenever I need to.

Feel free to use my code.

Happy hacking!!!


regards

-E-