Python

Solve PyGame sh: smpeg-config: command not found in Fedora

31 Jan , 2013  

Installing PyGame via pip will showing this problems. The easy is installing from yum by:

1
sudo yum install pygame

,

NodeJS,Python

Example create socket connection between Node JS and Python

30 Jan , 2013  

I build an experiment which is a multiplayer Pong game that using NodeJS and Django. This game need to build communication between browser in mobile phone as GamePad and browser in my laptop as display. Then, I facing this performance issue which there are delay between button get pressed in mobile browser and pong bar movement in laptop.

Then, I try to make it faster by change the display from browser into Python GUI. I’m wondering if I can make socket connection between displayer and NodeJS, it will gain performance 100% since there no websocket anymore.

After look at few documentation, I do a small stuff to make NodeJS can communicate with Python using socket.
More…

,

OS

Synergy between Mac and Linux and solve connection refused problem

30 Jan , 2013  

To make Synergy works in both Mac (as client) and Linux (as server), we should do this things:

1. Make sure have same version
If synergy version on client and server different, then connection problem will be occur.
So make sure we installing same version on both client and server.

2. Use Version 1.3.7
I found problem when using the latest version, then i rollback into 1.3.7 version and the connection problem is gone. Fyi, I use Mac OS X Snow Leopard and Fedora 18.

3. Configuration
There no special configuration here. For Fedora, I use this “/etc/synergy.conf”:

1
2
3
4
5
6
7
8
9
section: screens
    fedora:
    mac:

section: links
    fedora:
        left = mac
    mac:
        right = fedora

In this case, fedora is my hostname. So I just add “mac” in “/etc/hosts”:

1
192.168.1.3 mac

4. Run
In Fedora, i run synergys by :

1
synergys -f

In Mac OS X, i run synergyc by:

1
 ./synergyc -f 192.168.1.4

Which 192.168.1.4 is my Fedora IP address. Now we can share screen between Mac OS X and Linux :D

,

Django

Django models objects get attribute fields using string

28 Jan , 2013  

We can get django objects fields using string by “getattr”. For instance, I have profile objects.

1
getattr(profile, "name")

Easy! :D

Django

Find foreign key fields in Django models

28 Jan , 2013  

On some spesific task, we need to list all fields on object and identify which that have foreign key type.
For instance I have “profile” objects taken from Profile models.

1
2
3
4
profile = Profile.objects.get(id=1)

# get all fields
profile._meta.fields

Now, to identify which fields that ForeignKey type, we can iterate through the fields and check on “rel” attribute. rel is None if not relation and it will have a value if it has relation to another models.

1
2
3
for p in profile._meta.fields:
    if p.rel:
        // do your logic here

NodeJS

Example using Express 3 and Socket.io on the same ports

27 Jan , 2013  

Here is a quick example of using Express and Socket.io together. Usually, you landed into this pages because having problem like “express socket.io not found”, “static files in express to find socket.io.js” or someother else.

1. package.json

1
2
3
4
5
6
{
 "name" : "example-express-socketio",
 "version" : "0.1.0",
 "dependencies" : {"socket.io" : "0.9.6",
                   "express": "3.0.0"}
}

2. server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
var express = require('express'),
    socketio = require('socket.io'),
    app = express();
    http = require('http');

app.use("/", express.static(__dirname));

var server = http.createServer(app);
var io = socketio.listen(server);

var index = "<!doctype html>
             <html>
               <head>
                   <script src=/socket.io/socket.io.js></script>
                       <script>
                               var socket = io.connect('http://192.168.2.6:4000');
                               function test() {
                                            socket.emit('foo', 'Boo', function(data) {
                                                    alert(data);
                                    });
                                }
                        </script>
                </head>
                <body>
                <button onclick='test();'>Test</button>
            </html>";

app.get('/', function(req, res) {
    res.send(index);
});

io.sockets.on('connection', function(socket) {
    socket.on('foo', function(name, f) {
            f('Hello ' + name);
    });
});

server.listen(4000, "0.0.0.0");

Remember to change this “http://192.168.2.6:4000″ into yours IP or localhost.

3. Run

1
node server.js

and open “http://localhost:4000″.

Voila! :D

,

OS

Setup httpd conf virtualhost apache in Fedora 18

24 Jan , 2013  

Configuring apache / httpd in Fedora 18 to works with custom folder like “htdocs” and do the directory listing index is a bit irritating. Here is the errors that you might be facing like:

1
2
3
4
AH01630: client denied by server configuration
htaccess: allow not allowed here
AH01276: Cannot serve directory /var/www/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive
AH00035: access to / denied (filesystem path '/home/yodi/htdocs') because search permissions are missing on a component of the path

Here is the clue how to fix httpd virtualhost problem in Fedora 18

1. Custom /var/www/ path for virtualhost
To make custom folder works, we need to set that User/Group apache can access that folder. Or we can change into our user. For instance in “/etc/httpd/conf/httpd.conf”:
More…

,

OS

Fix httpd apache wont start problem in Fedora 18

23 Jan , 2013  

I found that I can’t start httpd / apache services in Fedora 18. There is several problem here. Let’s go to the first problem by running “service httpd start” :

1
2
Redirecting to /bin/systemctl restart  httpd.service
Job for httpd.service failed. See 'systemctl status httpd.service' and 'journalctl -xn' for details.

This give me errors :

1
sudo systemctl status httpd.service

and the results is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
httpd.service - The Apache HTTP Server
          Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled)
          Active: failed (Result: exit-code) since Wed 2013-01-23 17:29:43 SGT; 59s ago
         Process: 3322 ExecStop=/usr/sbin/httpd $OPTIONS -k graceful-stop (code=exited, status=0/SUCCESS)
         Process: 3320 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
          Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"

Jan 23 17:29:43 fedora httpd[3320]: AH00557: httpd: apr_sockaddr_info_get() failed for fedora
Jan 23 17:29:43 fedora httpd[3320]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 1... message
Jan 23 17:29:43 fedora systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Jan 23 17:29:43 fedora httpd[3322]: AH00557: httpd: apr_sockaddr_info_get() failed for fedora
Jan 23 17:29:43 fedora httpd[3322]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 1... message
Jan 23 17:29:43 fedora httpd[3322]: httpd (no pid file) not running
Jan 23 17:29:43 fedora systemd[1]: Failed to start The Apache HTTP Server.
Jan 23 17:29:43 fedora systemd[1]: Unit httpd.service entered failed state

More…

,

OS

How to change Grub OS order in Fedora 18

23 Jan , 2013  

There is a change in grub.cfg in Fedora 18. Right know, it’s not located in “/boot/grub2/” anymore.
You can find it on “/boot/efi/EFI/fedora/grub.cfg”. Here is the example of changing the OS order sequence:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
...

### BEGIN /etc/grub.d/10_linux ###
menuentry 'Fedora' --class fedora --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-69bfc31f-6ea3-4f28-aa18-6ef94dc3eed8' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt4'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt4 --hint-efi=hd0,gpt4 --hint-baremetal=ahci0,gpt4  e813e703-36da-4c68-8c81-83240b9760f2
        else
          search --no-floppy --fs-uuid --set=root e813e703-36da-4c68-8c81-83240b9760f2
        fi
        echo    'Loading Linux 3.6.10-4.fc18.x86_64 ...'
        linuxefi /vmlinuz-3.6.10-4.fc18.x86_64 root=/dev/mapper/fedora_fedora-root ro rd.md=0 rd.dm=0 rd.lvm.lv=fedora_fedora/swap rd.lvm.lv=fedora_fedora/root  rd.luks=0 vconsole.keymap=us rhgb quiet
        echo    'Loading initial ramdisk ...'
        initrdefi /initramfs-3.6.10-4.fc18.x86_64.img
}
submenu 'Advanced options for Fedora' $menuentry_id_option 'gnulinux-advanced-69bfc31f-6ea3-4f28-aa18-6ef94dc3eed8' {
        menuentry 'Fedora, with Linux 3.6.10-4.fc18.x86_64' --class fedora --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.6.10-4.fc18.x86_64-advanced-69bfc31f-6ea3-4f28-aa18-6ef94dc3eed8' {
                load_video
                set gfxpayload=keep
                insmod gzio
                insmod part_gpt
                insmod ext2
                set root='hd0,gpt4'
                if [ x$feature_platform_search_hint = xy ]; then
                  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt4 --hint-efi=hd0,gpt4 --hint-baremetal=ahci0,gpt4  e813e703-36da-4c68-8c81-83240b9760f2
                else
                  search --no-floppy --fs-uuid --set=root e813e703-36da-4c68-8c81-83240b9760f2
                fi
                echo    'Loading Linux 3.6.10-4.fc18.x86_64 ...'
                linuxefi /vmlinuz-3.6.10-4.fc18.x86_64 root=/dev/mapper/fedora_fedora-root ro rd.md=0 rd.dm=0 rd.lvm.lv=fedora_fedora/swap rd.lvm.lv=fedora_fedora/root  rd.luks=0 vconsole.keymap=us rhgb quiet
                echo    'Loading initial ramdisk ...'
                initrdefi /initramfs-3.6.10-4.fc18.x86_64.img
        }
}

menuentry 'Fedora (3.7.2-204.fc18.x86_64)' --class fedora --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-69bfc31f-6ea3-4f28-aa18-6ef94dc3eed8' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt4'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt4 --hint-efi=hd0,gpt4 --hint-baremetal=ahci0,gpt4  e813e703-36da-4c68-8c81-83240b9760f2
        else
          search --no-floppy --fs-uuid --set=root e813e703-36da-4c68-8c81-83240b9760f2
        fi
        echo 'Loading Fedora (3.7.2-204.fc18.x86_64)'
        linuxefi /vmlinuz-3.7.2-204.fc18.x86_64 root=/dev/mapper/fedora_fedora-root ro rd.md=0 rd.dm=0 rd.lvm.lv=fedora_fedora/swap rd.lvm.lv=fedora_fedora/root  rd.luks=0 vconsole.keymap=us rhgb quiet LANG=en_US.UTF-8
        echo 'Loading initial ramdisk ...'
        initrdefi /initramfs-3.7.2-204.fc18.x86_64.img
}
### END /etc/grub.d/10_linux ###

...

You can move the “menuentry” menu there.

,

Python

Example encode and decode image using base64 in Python

22 Jan , 2013  

This is the simple way to encode images using base64 library in Python and decoded it back into the images based on the string encoded results. Here is the code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import base64

def convert(image):
    f = open(image)
    data = f.read()
    f.close()

    string = base64.b64encode(data)
    convert = base64.b64decode(string)

    t = open("example.png", "w+")
    t.write(convert)
    t.close()

if __name__ == "__main__":
    convert("test.png")

In this example, I put “test.png” images into the same level of this scripts. Happy encoding & decoding! :D

OS

Solve creating file buffer problem that make Aptana very slow

21 Jan , 2013  

I notice this today which I download the latest Aptana and run it under Fedora 18. It’s very slow and every time opening a new file, I got “creating file buffer” notification and takes like 1-3 minutes to finish. Then I realize the problem because the Java version I use.

In Fedora 18, by default it will using OpenJDK which caused this slow opening file issue. To solve this problem, we just need switch into using Oracle Java version rather using the OpenJDK.

,

OS

Guide setup Fedora 18 in Macbook Pro

21 Jan , 2013  

Here is the full guide setup Fedora 18 Spherical Cow in Macbook Pro.

1. Install Wireless
Please follow my another tutorial :
http://www.yodi.sg/fix-broadcom-wireless-not-working-in-fedora-18/.

2.Install development packages

1
2
3
sudo yum install make automake gcc gcc-c++ libxslt libxslt-devel libxml2 libxml2-devel libffi libffi-devel libcurl libcurl-devel openssl-devel sqlite-devel libXv.i686 libXScrnSaver.i686 qt.i686 qt-x11.i686 libxslt-devel
sudo yum install postgresql-server postgresql-devel nmap ImageMagick git
sudo yum install yakuake shutter vlc libreoffice k3b kdepim

3. Setup LAMPP

1
sudo yum install mysql mysql-server mysql-devel nginx php php-fpm php-common phpmyadmin httpd

run “sudo mysql_secure_installation” if you don’t want root with blank password.

1
2
3
4
sudo systemctl start httpd.service
sudo systemctl enable httpd.service
sudo systemctl start mysqld.service
sudo systemctl enable mysqld.service

For PhpMyadmin configuration is located in : “/etc/phpMyAdmin/config.inc.php”.
To make Phpmyadmin work without password, change this line :

1
$cfg['Servers'][$i]['AllowRoot']     = TRUE;        // whether to allow root login

And don’t forget to reload your webserver.

4. Skype 2.2
I love to use old Skype. You can download from http://repo.fedora.md/3rdparty/.

5. NodeJS and Redis
NodeJS and Redis is a must in software development, so we can install this both great software by :

1
2
3
4
sudo yum --enablerepo=updates-testing install nodejs
sudo yum install redis
sudo systemctl start redis.service
sudo systemctl enable redis.service

More…

OS

Fix Broadcom Wireless not working in Fedora 18

20 Jan , 2013  

Fedora 18 “Spherical Cow” have problem with wireless driver. I use macbook Pro at this example, and here is my wireless by “lspci” :

1
2
02:00.0 Network controller: Broadcom Corporation BCM4322 802.11a/b/g/n Wireless LAN Controller (rev 01)
03:00.0 Ethernet controller: Broadcom Corporation NetXtreme BCM5764M Gigabit Ethernet PCIe (rev 10)

Then I need to install the “broadcom-wl” package by:

1
sudo yum install kmod-wl-`uname -r`

UPDATE
Update Fedora to the latest kernel (3.7.4-204.fc18.x86_64) will solve this wireless problem which that mean no need to disable “ssb” since isn’t loaded as default.

Then this is the magic :

1. Remove SSB module that make the wireless can’t works

1
sudo rmmod ssb

2. add blacklist ssb into modprobe
Then we need to edit and add “blacklist ssb” into “/etc/modprobe.d/blacklist.conf”.

3. Enable wireless

1
sudo modprobe wl

Voilla! Now our wireless working in Fedora 18! :D

,

Django,Python

Example XMLRPC communication between Django and Java

18 Jan , 2013  

XMLRPC is useful when we need to send / receive information from one platform to others. In this case, I will use Django as the server which provide services that can be accessed as XMLRPC method from Java.

First, we need to setup Django projects and set the XMLRPC server. In quick way, I use “django-xmlrpc” and the source code can be taken from my Github https://github.com/yodiaditya/python-collection/tree/master/djangoserver. I have method called “test” which can be accessed through simple python script :

1
2
3
import xmlrpclib
s = xmlrpclib.ServerProxy("http://127.0.0.1:8000/xmlrpc/")
s.test('test')

It will give result “test World!”.

Now how about in Java? There are several XMLRPC library, at this example I will use XMLRPC library from Apache.
More…

,

Android

Solve android XMLRPC client can’t connect to 127.0.0.1 or localhost

18 Jan , 2013  

When you got error that your Android application can’t do XMLRPC client to host like 127.0.0.1 or localhost or some IP address like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
01-16 03:45:06.650: W/System.err(7414): org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.4:8000 refused
01-16 03:45:06.660: W/System.err(7414):         at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:178)
01-16 03:45:06.660: W/System.err(7414):         at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-16 03:45:06.660: W/System.err(7414):         at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-16 03:45:06.660: W/System.err(7414):         at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
01-16 03:45:06.660: W/System.err(7414):         at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-16 03:45:06.660: W/System.err(7414):         at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-16 03:45:06.660: W/System.err(7414):         at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-16 03:45:06.660: W/System.err(7414):         at org.xmlrpc.android.XMLRPCClient.callEx(XMLRPCClient.java:178)
01-16 03:45:06.660: W/System.err(7414):         at org.xmlrpc.android.XMLRPCClient.call(XMLRPCClient.java:281)
01-16 03:45:06.660: W/System.err(7414):         at zin.my.rashidi.android.demo.xmlrpc.LoginActivity$1.onClick(LoginActivity.java:43)
01-16 03:45:06.670: W/System.err(7414):         at android.view.View.performClick(View.java:2485)
01-16 03:45:06.670: W/System.err(7414):         at android.view.View$PerformClick.run(View.java:9080)
01-16 03:45:06.670: W/System.err(7414):         at android.os.Handler.handleCallback(Handler.java:587)
01-16 03:45:06.670: W/System.err(7414):         at android.os.Handler.dispatchMessage(Handler.java:92)
01-16 03:45:06.670: W/System.err(7414):         at android.os.Looper.loop(Looper.java:130)
01-16 03:45:06.670: W/System.err(7414):         at android.app.ActivityThread.main(ActivityThread.java:3687)
01-16 03:45:06.670: W/System.err(7414):         at java.lang.reflect.Method.invokeNative(Native Method)
01-16 03:45:06.670: W/System.err(7414):         at java.lang.reflect.Method.invoke(Method.java:507)
01-16 03:45:06.670: W/System.err(7414):         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
01-16 03:45:06.670: W/System.err(7414):         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
01-16 03:45:06.670: W/System.err(7414):         at dalvik.system.NativeStart.main(Native Method)
01-16 03:45:06.680: W/System.err(7414): Caused by: java.net.ConnectException: /192.168.1.4:8000 - Connection refused
01-16 03:45:06.690: W/System.err(7414):         at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:207)
01-16 03:45:06.690: W/System.err(7414):         at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
01-16 03:45:06.690: W/System.err(7414):         at java.net.Socket.connect(Socket.java:1002)
01-16 03:45:06.690: W/System.err(7414):         at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-16 03:45:06.690: W/System.err(7414):         at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
01-16 03:45:06.690: W/System.err(7414):         ... 20 more
01-16 03:45:06.700: W/System.err(7414): org.xmlrpc.android.XMLRPCException: org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.4:8000 refused
01-16 03:45:06.700: W/System.err(7414):         at org.xmlrpc.android.XMLRPCClient.callEx(XMLRPCClient.java:237)
01-16 03:45:06.700: W/System.err(7414):         at org.xmlrpc.android.XMLRPCClient.call(XMLRPCClient.java:281)
01-16 03:45:06.700: W/System.err(7414):         at

More…

,

Python

Aware with the way Python treat and re-use existing objects

18 Jan , 2013  

Python has a unique way when creating and re-using objects. See this example :

1
2
3
4
5
6
7
8
def x(y=[]):
    y.append("1")
    return y

if __name__ == "__main__":
    print x()
    print x()
    print x()

This will showing result:

1
2
3
['1']
['1', '1']
['1', '1', '1']

Why this is happen? See the logic behind. When the objects y which is not exists, Python will create this objects once the first x() executed. Then come to next of x() execution which Python interpreter will looking for the y and check whether it’s exists or not. If the objects exists, then Python will re-use it and we see the “['1', '1']” result on second execution.

,

Python

Converting image with Base64 encode will give bigger results size

18 Jan , 2013  

Base64 usually needed to represent binary data into ASCII format, or in other case to make it more “readable”. Some case study why we need to convert binary into ASCII like this :

1. There is Android App that have function to take picture
2. This picture will send to website
3. In Website (Django eg) it will have method to handle the picture

When we using POST binary data, there will issue like CSRF_TOKEN, filesize, resume feature, etc. It will hard thing to track the percentage of binary data by the size. Using base64 by encode the image will be a good solution to tackle this problem. Instead of using POST data, we can use XML-RPC and send the “string” of the photos. Later on we can decode back into binary data.

On interesting fact here that base64 encode results will be 1.37 bigger than the actual binary data.
Here is to do in python:

1
2
3
4
5
6
7
8
9
import base64

f = open("grimace.jpg")
encoded = base64.b64encode(f.read())
f.close()

a = open("grimace.txt", "w+")
a.write(encoded)
a.close()

And the results by using “ls” :

1
2
26545 grimace.jpg
35396 grimace.txt

Why it’s get bigger? Because we represent the binary (01111) into ASCII which it take 8 bit and plus with the headers of the files.

,

Django

Solve load font face Cloudfront, Amazon S3 and Firefox / IE caused by CORS access control allow origin *

17 Jan , 2013  

Usually we try host our custom font into Amazon S3, cached by Cloudfront and use it into our website. If you can’t load your font using font face from Firefox / IE, this posting is match for your problem. This problem mostly occur on Firefox and IE because this browser have restriction on Cross Origin Resource Sharing which in short way called “CORS” and no “access control allow origin *” headers. But why this problem didn’t occur in Chrome? Because in Chrome, it’s doesn’t care about CORS rule which in other word, Chrome will allow resource from another domain.

In a short description, to solve font-face problems in Firefox and IE, yours font must be have this headers:

1
Access-Control-Allow-Origin header *

Unfortunately, eventhough you set the CORS in Amazon S3 to allow origin headers, but it wouldn’t solve the problem.
Because right know, it’s still doesn’t have option to add “Access-Control-Allow-Origin” header.
More…

,

Django

Setup WSGI Apache for Django 1.4 Production

16 Jan , 2013  

Here is the example of wsgi under your / /wsgi.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""
WSGI config for bodyslap project.

This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.

Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.

"""

# Django wsgi for apache
import os
import sys
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

# django project absolute path
sys.path.append(os.path.join(PROJECT_PATH, '..'))
sys.path.append(os.path.join(PROJECT_PATH))

from settings import DEBUG

if not DEBUG:
    import monitor
    monitor.start(interval=1.0)
    monitor.track(os.path.join(os.path.dirname(__file__), '..'))

# django core location
sys.path.append('/usr/local/lib/python2.7/dist-packages/django/')

# Your django settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'bodyslap.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

,

Django

I select particular number of item in selection on Lettuce test

15 Jan , 2013  

I select particular number of item in selection on Lettuce test and simply by:

1
2
3
4
@step('I select item "([^"]*)" from "([^"]*)"')
def i_select_item_number_from_select(step, number, select_name):
    world.browser.find_by_xpath('//select[@name="%s"]/option[%s]' %
                                (select_name, number)).click()

Python

Python try except exception showing the message error

9 Jan , 2013  

When we don’t know about what the kind of error that throwed by try: … except: .., we can just print out the message by:

1
except Exception, e:

And get the error from “message” attribute of “e”. For instance:

1
2
3
4
5
6
a = []

try:
    a[100]
except Exception, e:
    print e.message

Django

Fix Django RuntimeError: Settings already configured when executed scripts manually

8 Jan , 2013  

Sometimes we need to create independent files that need to load Django environment and to get executed manually outside from Django apps. For instance, we need to create backup.py which will backup the django project database but read settings.py for the database configuration.

Usually, we can do on this way, assume the files located in PROJECT/APPS/UTILS/backup.py

1
2
3
4
5
6
7
8
import os
import sys

# Load environment
CURRENT = os.path.abspath(os.path.dirname(__file__))
PROJECT = os.path.abspath(os.path.join(CURRENT, "..", ".."))

sys.path.insert(1, PROJECT)

Sometime this is works and sometime doesn’t like having error :

1
RuntimeError: Settings already configured.

To solve this problems, we need to change the way to load sys.path from “append” into “insert”. Because the problem was PROJECT is on last order in sys.path. Here is the solution

1
2
3
4
5
6
7
8
import os
import sys

# Load environment
CURRENT = os.path.abspath(os.path.dirname(__file__))
PROJECT = os.path.abspath(os.path.join(CURRENT, "..", ".."))

sys.path.insert(1, PROJECT)

,