Showing posts with label playdoh. Show all posts
Showing posts with label playdoh. Show all posts

Friday, October 21, 2011

Setting up more Django on a clean Ubuntu server

Get virtualenvs and virtualenvwrapper following this and this and this (with an informative video)

On root account:
1. sudo apt-get install python-setuptools

2. sudo easy_install virtualenv

3.
virtualenv ve_msw
New python executable in ve_msw/bin/python
Installing setuptools............done.
Installing pip...............done.

4. easy_install pip (I could also have done "pip install virtualenv" or "easy_install virtualenvwrapper"

5. pip install virtualenvwrapper

On user account:
6. mkdir ~/.virtualenvs

7. Add to end of ~/.bashrc:
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

8.
$ mkvirtualenv ve_msw
New python executable in ve_msw/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /home/haoqili/.virtualenvs/ve_msw/bin/predeactivate
virtualenvwrapper.user_scripts creating /home/haoqili/.virtualenvs/ve_msw/bin/postdeactivate
virtualenvwrapper.user_scripts creating /home/haoqili/.virtualenvs/ve_msw/bin/preactivate
virtualenvwrapper.user_scripts creating /home/haoqili/.virtualenvs/ve_msw/bin/postactivate
virtualenvwrapper.user_scripts creating /home/haoqili/.virtualenvs/ve_msw/bin/get_env_details

9. Added to ~/.virtualenvs/postmkvirtualenv
proj_name=$(echo $VIRTUAL_ENV|awk -F'/' '{print $NF}')
mkdir $HOME/Projects/$proj_name
add2virtualenv $HOME/Projects/$proj_name
cd $HOME/Projects/$proj_name
easy_install readline ipython
pip install -e git://github.com/jbalogh/check.git#egg=check Jinja2==2.3.1 \
    MySQL-python==1.2.3c1 lxml==2.2.6 PIL

10. Now I can call workon ve_msw

MSW already have playdoh set up at the very beginning
11. To set up where virtualenvwrapper's "workon" takes us to add this to
~/.virtualenvs/ve_msw/bin/postactivate
cd ~/path/to/mswdir

Tuesday, July 19, 2011

My Project's Packages

Todo:

1. update my own vendor with git clone --recursive git://github.com/mozilla/playdoh-lib.git ./vendor from playdoh doc

2. clean up my imports

3. clean up my vendor-local from virutal enviorments below from /Users/haoqili/.virtualenvs/playdoh/lib/python2.7/site-packages


haoqili@host-3-248:15:44:10:~/.virtualenvs/playdoh/lib/python2.7/site-packages$ ls -l
total 1016
drwxr-xr-x  11 haoqili  staff     374 Jun 15 10:39 Crypto
drwxr-xr-x   4 haoqili  staff     136 Jun 30 09:41 Django-1.3-py2.7.egg
drwxr-xr-x  10 haoqili  staff     340 Jun  6 14:58 Jinja2-2.5.5-py2.7.egg-info
drwxr-xr-x   7 haoqili  staff     238 Jun  6 14:58 MySQL_python-1.2.3c1-py2.7.egg-info
drwxr-xr-x  15 haoqili  staff     510 Jun  6 14:58 MySQLdb
drwxr-xr-x  12 haoqili  staff     408 Jun 15 11:44 OpenSSL
drwxr-xr-x   4 haoqili  staff     136 Jun 15 10:09 Twisted-11.0.0_r32122-py2.7-macosx-10.4-x86_64.egg
-rwxr-xr-x   1 haoqili  staff   18328 Jun  6 14:58 _hashlib.so
-rwxr-xr-x   1 haoqili  staff   70072 Jun  6 14:58 _mysql.so
-rw-r--r--   1 haoqili  staff    2306 Jun  6 14:57 _mysql_exceptions.py
-rw-r--r--   1 haoqili  staff    4559 Jun  6 14:58 _mysql_exceptions.pyc
drwxr-xr-x   5 haoqili  staff     170 Jun 14 16:40 backports
drwxr-xr-x   7 haoqili  staff     238 Jun 14 16:40 backports.ssl_match_hostname-3.2a3-py2.7.egg-info
drwxr-xr-x   5 haoqili  staff     170 Jun  6 14:54 bcrypt
-rw-r--r--   1 haoqili  staff      48 Jun 13 12:00 bleach.egg-link
-rw-r--r--   1 haoqili  staff    6032 Jul  6 13:44 django_csp-1.0.1-py2.7.egg
-rw-r--r--   1 haoqili  staff    6854 Jun 30 09:41 django_ratelimit-0.1-py2.7.egg
drwxr-xr-x   7 haoqili  staff     238 Jun 29 19:46 django_registration-0.7-py2.7.egg-info
-rw-r--r--   1 haoqili  staff     509 Jul  6 13:44 easy-install.pth
drwxr-xr-x   7 haoqili  staff     238 Jun  6 14:58 hashlib-20081119-py2.7.egg-info
-rw-r--r--   1 haoqili  staff    4993 Jun  6 14:58 hashlib.py
-rw-r--r--   1 haoqili  staff    4452 Jun  6 14:58 hashlib.pyc
drwxr-xr-x   9 haoqili  staff     306 Jun  6 14:58 hmac-20101005-py2.7.egg-info
-rw-r--r--   1 haoqili  staff    4531 Jun  6 14:57 hmac.py
-rw-r--r--   1 haoqili  staff    4892 Jun  6 14:58 hmac.pyc
drwxr-xr-x  24 haoqili  staff     816 Jun 13 12:00 html5lib
drwxr-xr-x   7 haoqili  staff     238 Jun 13 12:00 html5lib-0.90-py2.7.egg-info
drwxr-xr-x  49 haoqili  staff    1666 Jun  6 14:58 jinja2
drwxr-xr-x   4 haoqili  staff     136 Jun  6 14:23 pip-1.0.1-py2.7.egg
drwxr-xr-x   8 haoqili  staff     272 Jun 15 11:44 pyOpenSSL-0.12-py2.7.egg-info
drwxr-xr-x   7 haoqili  staff     238 Jun  6 14:54 py_bcrypt-0.2-py2.7.egg-info
-rw-r--r--   1 haoqili  staff     629 Jun 15 10:46 pycrypto-2.0.1-py2.7.egg-info
-rw-r--r--   1 haoqili  staff    8399 Jun 29 20:31 recaptcha_client-1.0.6-py2.7.egg
drwxr-xr-x  18 haoqili  staff     612 Jun 29 19:46 registration
-rw-r--r--   1 haoqili  staff  332005 Jun  6 14:12 setuptools-0.6c11-py2.7.egg
-rw-r--r--   1 haoqili  staff      30 Jun 15 10:09 setuptools.pth
drwxr-xr-x   4 haoqili  staff     136 Jun 15 10:09 zope.interface-3.6.3-py2.7-macosx-10.4-x86_64.egg

Django Playdoh Package Locations

I was confused when reading how to add packages and seeing that packages live in different locations.

jsocol clarified:

/packages is old-and-busted, use lib/python for non-git things
but you can't put any libraries with compiled components into the vendor lib (it means vendor can't contain anything with c/c++ components)
it's just a question of installing via git (or, well, pip install vcs+vcs://) or using PyPI and the name (e.g. "pip install foo")


pip install foo gives vendor-local/lib/python/foo

using git to install foo gives vendor-local/src/foo



This is what I did, with help from groovecoder. :D

playdoh (master)$ pip install --no-install --build=vendor-local/packages --src=vendor-local/src -I cef
Downloading/unpacking cef
  Downloading cef-0.2.tar.gz
  Running setup.py egg_info for package cef
    
Successfully downloaded cef

And then I found that cef is inside vendor-local/packages. :D

Now I need to add this path to vendor.pth. Groovecoder told me that "*.pth files are automatically included by the python interpreter"

playdoh/vendor-local (master)$ cat vendor.pth 
packages/cef

Now I can use cef!
playdoh (master)$ python manage.py shell
...
>>> from cef import log_cef
>>>

I could also have done
/playdoh (master)$ pip install -I --install-option="--home=`pwd`/vendor-local" cef
Downloading/unpacking cef
  Downloading cef-0.2.tar.gz
  Running setup.py egg_info for package cef
    
Installing collected packages: cef
  Running setup.py install for cef
    
Successfully installed cef
Cleaning up...
and have
playdoh/vendor-local/lib/python (master)$ ls
cef-0.2-py2.7.egg-info cef.py                 cef.pyc

Tuesday, June 28, 2011

vendor makes python Django possible

$ python manage.py runserver 8005
Traceback (most recent call last):
File "manage.py", line 5, in
from django.core.management import execute_manager
ImportError: No module named django.core.management

[2:52pm] haoqili: django setup question: why is my "python manage.py runserver" working when I can't "import django" in python?
[2:53pm] wenzel: haoqili: django is part of the vendor/ dir
[2:53pm] wenzel: which is not in Python's standard library path
[2:53pm] haoqili: okay
[2:53pm] wenzel: buuut, manage.py puts it into the library path
[2:53pm] wenzel: edit manage.py and look for site.addsitedir (or something like that)
[2:53pm] jsocol: you can do `python manage.py shell`
[2:53pm] wenzel: that's what puts the vendor/ dir on the list of places where Python looks for imports

Tuesday, June 14, 2011

Tutorial: Make Ajax Form in Django + Bleach Sanitization on Playdoh + Jingo + Jinja

You can see the final version of complete files here.


1. Import bleach.

2. Make a new (dummy) url
2: in urls.py
(r'^richtext$', 'richtext'),

3. models.py: Make a new model. Go to SQL to add some initial entries into the model.

My model, RichText, looks like this:
3: in models.py:
from django.db import models
class RichText(models.Model):
    name = models.CharField(max_length=200)
    comment = models.TextField()

4. models.py: Make a form associated with that model, it's a Django ModelForm.

5. models.py: Clean the commented data through bleach.clean()


5a. clean_<fieldname>(): Note that the method name "clean_comment" is not chosen arbitrarily. It must start with "clean_" and the 2nd part must match with one of the fields of the model.


5b. cleaned_data[]: is like POST[] or REQUST[], but with cleaned_data, the "data has not only been validated but will also be converted in to the relevant Python types".

5c. Finally do a bleach.clean on the data before it's returned.

4+5: in models.py:
from django.forms import ModelForm
class RichTextForm(ModelForm):
    class Meta:
        model = RichText

    def clean_comment(self): #comment must match one of the fields of model
        data = self.cleaned_data['comment']
        return bleach.clean(data)

6. richtext.html: Make the Django form's html
<form id="myform" action="" method="post">
    {{ csrf() }}
    {{ form.as_p() }}
<input type="submit" value="Submit" />
</form>

You might get an CRSF error at this point... keep reading

Note that the "CSRF()" is different from how Django usually contains it, it's explained here and in the flip below:.
CSRF Explanation
Django's fix to CSRF can be found in [https://docs.djangoproject.com/en/dev/intro/tutorial04/ the tutorial]. Where you put in

template.html:
{% csrf_token %}

views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
def ...
    return render_to_response('template.html', {'var_name': var_value}, context_instance=RequestContext(request))

But in the demo's setup with jingo and other stuff:
template.html:
{{ csrf() }}
views.py:
import jingo
    return jingo.render(request, 'template.html', {"var_name": var_value})

7. richtext.html: add AJAX to submit form and display all results
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">
</script>
    <div id="results">
    {% include 'msw/richtext_table.html' %}
</div>
    <script>
        $("#myform").submit(function(){
            $.post(location.href, $('#myform').serialize(), function(d) {
$('#results').html(d);   
});
            return false;
        })
    </script>

If the HTML is not rendered, use "|safe".
richtext_table.html:
    {% if all_richtext_list %}
        {% for richtext in all_richtext_list %}
            <p>Name title: <b>{{ richtext.name|safe }}</b> says: <b>{{ richtext.comment|safe }}</b></p>
        {% endfor %}
    {% else %}
        <p>No comments are available.</p>
    {% endif %}

8. views.py: Save new Django AJAX form inputs

NOTE: There are 2 different template filenames. The "_table.html" is there so that whenever there is a post, ONLY the output table is rendered. Without that line, the entire page would be rendered!!

import bleach
from msw.models import RichText, RichTextForm
...

def richtext(request):
    file = 'msw/richtext.html'
    if request.method == "POST":
        form = RichTextForm(request.POST)
        if form.is_valid():
            form.save()
        file = 'msw/richtext_table.html'
    else:
        form = RichTextForm()
    return jingo.render(request, file, {"form": form, "title_chunk" : "Bleach Testing:", "all_richtext_list": RichText.objects.all()})


You can see the final version of complete files here.

Monday, June 13, 2011

Server Certificate stuff for SSL

Playdoh/Django server setup doc:
docs/operations.rst:Apps are typically run under Apache and mod_wsgi in production. Entry point: wsgi/playdoh.wsgi

Got openssl, I found the executable openssl in /usr/local/ssl/bin. And replaced the old openssl in /usr/bin with it.

Followed this for setting up (copied below in flip panel) a certificate:


Generating a Private Key and CSR
    $ openssl genrsa -des3 -out server.key 1024
    $ openssl rsa -in server.key -out server.pem
    $ openssl req -new -key server.key -out server.csr

Generating a Self-Signed Certificate
    $ openssl x509 -req -days 120 -in server.csr -signkey server.key -out server.crt

vendor/src/django/docs/howto/apache-auth.txt

Support for mod_python has been deprecated within Django. At that time, this method of authentication will no longer be provided by Django. The community is welcome to offer its own alternate solutions using WSGI middleware or other approaches.



vendor/src/django/docs/topics/install.txt. and Django with wsgi


me: It's a wsgi server
super: isn't wsgi a mod to allow django to work with apache?
me: I'll google about it
super: i'm pretty sure it is. if so, then you can just do the cert install per normal apache process
...
...
me: I'm failing to find some files: apache/etc/ssl.conf and httpd.conf
Do you know where they are?
super: normally i believe they are in /etc
me: are they supposed to be on my local machine ... not on playdoh?
super: it is installed by playdoh
*came to desk and did the following:*

$ ps -a
  704 ttys000    0:56.66 /Users/haoqili/.virtualenvs/playdoh/bin/python ./manage.py runserver

This is Django's bulit-in web server :(

:( have to install Apache. --> put off till later --> ask webdev people

Do it later.

click here for a copy of slacksite's ssl certificate

Generating a Private Key and CSR

The openssl toolkit is used to generate an RSA Private Key and CSR (Certificate Signing Request). It can also be used to generate self-signed certificates which can be used for testing purposes or internal usage. The utility used to do all of these tasks is known simply as openssl. It should be installed in the /usr/local/ssl/bin directory. You may want to add this directory to your PATH, or copy or link the openssl utility to a directory that is already in your PATH so that you do not have to type the full path to the executable. The examples below will assume that opensslis in a location that is accessible to you without using the full path to the command.
The first step is to create your RSA Private Key. This key is a 1024 bit RSA key which is encrypted using Triple-DES and stored in a PEM format so that it is readable as ASCII text. We will use several files as random seed enhancers which will help to make the key more secure. Text files that have been compressed with a utility such as gzip are good choices. The key is generated using the following command, where file1:file2:etc represents the random compressed files.
$ openssl genrsa -des3 -rand file1:file2:file3:file4:file5 -out server.key 1024
The command will prompt you for a pass-phrase and then store the key in the file server.key. It is critical that the pass-phrase be secure and not forgotten. If either the key is lost, or the pass-phrase is forgotten, the certificate will be useless! It cannot be stressed enough how important the private key is to the certificate. If the private key and pass-phrase are compromised, the certificate will have to be revoked, costing you the price of the certificate all over again if you have paid an authority for the certificate. It may be a wise idea to back this file up to secure media, such as tape or diskette.
One unfortunate side-effect of the pass-phrased private key is that Apache will ask for the pass-phrase each time the web server is started. Obviously this is not necessarily convenient as someone will not always be around to type in the pass-phrase, such as after a reboot or crash. mod_ssl includes the ability to use an external program in place of the built-in pass-phrase dialog, however, this is not necessarily the most secure option either. It is possible to remove the Triple-DES encryption from the key, thereby no longer needing to type in a pass-phrase. If the private key is no longer encrypted, it is critical that this file only be readable by the root user! If your system is ever compromised and a third party obtains your unencrypted private key, the corresponding certificate will need to be revoked. With that being said, use the following command to remove the pass-phrase from the key:
$ openssl rsa -in server.key -out server.pem
Once the private key is generated a Certificate Signing Request can be generated. The CSR is then used in one of two ways. Ideally, the CSR will be sent to a Certificate Authority, such asThawte or Verisign who will verify the identity of the requestor and issue a signed certificate. The second option is to self-sign the CSR, which will be demonstrated in the next section.
During the generation of the CSR, you will be prompted for several pieces of information. These are the X.509 attributes of the certificate. One of the prompts will be for "Common Name (e.g., YOUR name)". It is important that this field be filled in with the fully qualified domain name of the server to be protected by SSL. If the website to be protected will be https://www.server.com, then enter www.server.com at this prompt. The command to generate the CSR is as follows:
$ openssl req -new -key server.key -out server.csr
A sample CSR generation session is shown below, with sample responses shown in bold:
$ openssl req -new -key server.key -out server.csr
Using configuration from /usr/local/ssl/openssl.cnf
Enter PEM pass phrase:Enter pass phrase here
You are about to be asked to enter information that will be incorporated into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank.
For some fields there will be a default value, If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New Hampshire
Locality Name (eg, city) []:Nashua
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Domain.com, Inc.
Organizational Unit Name (eg, section) []:.

Common Name (eg, YOUR name) []:www.domain.com
Email Address []:webmaster@domain.com


Please enter the following 'extra' attributes to be sent with your certificate request
A challenge password []:
An optional company name []:


Generating a Self-Signed Certificate

At this point you will need to generate a self-signed certificate because you either don't plan on having your certificate signed by a CA, or you wish to test your new SSL implementation while the CA is signing your certificate. In my experience dealing with Thawte, it can take up to a week or more before receiving your signed certificate. The time it takes to receive the certificate will vary based on how quickly they receive your required documentation. This temporary certificate will generate an error in the client browser to the effect that the signing certificate authority is unknown and not trusted.
To generate a temporary certificate which is good for 60 days, issue the following command:
$ openssl x509 -req -days 60 -in server.csr -signkey server.key -out server.crt


Installing the Private Key and Certificate

When Apache with mod_ssl is installed, it creates several directories in the Apache config directory. The location of this directory will differ depending on how Apache was compiled. If using my instructions on compiling Apache, the config directory is /usr/local/apache/etc. The directories mod_ssl creates include ssl.crt, ssl.csr, and ssl.key. These are good locations to store server certificates, CSRs, and private keys, respectively. If there will be multiple SSL enabled hosts on one server, it may be good practice to name the files with the fully qualified domain name of the SSL enabled host.
When adding SSL enabled virtualhosts to the web server, I prefer to keep all of the SSL virtualhosts in a separate file. This insures that all SSL hosts can be easily found in one location and helps to keep the httpd.conf file from growing too large. The SSL virtualhosts will be kept in a file called ssl.conf. In order for Apache to recognize and parse this file, it must be included in the httpd.conf file with the following directive:
Include /usr/local/apache/etc/ssl.conf


Configuring SSL Enabled Virtual Hosts

Extensive examples of SSL configurations for a virtualhost are included as part of the/usr/local/apache/etc/httpd.conf.default file installed with mod_ssl. Please refer to this file and to the mod_ssl documentation for more detailed information on configuration options. A basic SSL enabled virtualhost will appear as follows in the ssl.conf file:
# SSL Virtual Hosts
<IfDefine SSL>

<VirtualHost _default_:443>
ServerAdmin webmaster@domain.com
DocumentRoot /usr/local/apache/share/htdocs
ServerName www.domain.com
ScriptAlias /cgi-bin/ /usr/local/apache/share/htdocs/cgi-bin/
SSLEngine on
SSLCertificateFile /usr/local/apache/etc/ssl.crt/server.crt
SSLCertificateKeyFile /usr/local/apache/etc/ssl.key/server.pem
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
CustomLog /usr/local/apache/var/log/ssl_request_log \"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b" </VirtualHost>

</IfDefine>
This will create an SSL virtualhost named www.domain.com, which is accessed via port 443 (the standard port for https) on the default IP address of the web server. It is possible to add as many additional virtualhosts as there are IP addresses that the web server listens to. Simply add additional virtualhost blocks inside of the <IfDefine SSL> and </IfDefine> tags. Due to the nature of the SSL encryption of the HTTP traffic, it is NOT possible to have name-based (HTTP1.1) SSL virtual hosts. To create a new SSL virtualhost on a different IP address, simply replace _default_ with the IP address of the virtualhost.
After adding the virtualhost to the ssl.conf file, Apache must be killed and restarted in order for it to recognize the new virtualhost. Unfortunately, this is one of the rare instances where a simpleHUP signal will not work. After restarting the server, depending on whether the encrypted or unencrypted key was used, Apache will prompt you for the pass-phrase(s) of the SSL virtualhost(s). Enter the pass-phrase(s) and the web server will start.
Now, point your favorite browser to the new virtualhost you just created, remembering to use https:// instead of http://, and you should be greeted with a warning dialog if you are using the self-signed certificate. Acknowledge the dialog and the page will continue to load, protected by SSL. The status bar of your browser should be graced by the 'lock' icon, which signifies the page is protected via SSL. This is all there is to it!

Monday, June 6, 2011

Set up Playdoh and creating virtual enviroments

Mozilla

Playdoh < Django < Virtual Enviorment < MacBook

Playdoh is usually set us in ~/dev
Setup directions.

Set up another virtual environment like playdoh in dev, first use https://gist.github.com/1011209, then do mkvirtualenv [project name]

Set up adium chat for encrypted messages.