Get recent tweets using twitter 1.1 API (django + jquery)

Recently (11 June 2013) twitter has deactivated its 1.0 API. Things like getting a user’s recent tweets were so simple before, making a request to the next url on the client side solved the problem:

http://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=UserNickname&count=8

Now we need server side authentication to perform this. I have seen many scripts in php, and some plugins in Python but the only script in Python that worked for me was this nice script:

http://thomassileo.com/blog/2013/01/25/using-twitter-rest-api-v1-dot-1-with-python/

Next I have created a view on my django project that uses this script (I have specify the oAuth token, so I do not call setup_oauth function, but if we want we can include the whole __main__ code):

from django.http import HttpResponse
import json

def get_recent_tweets(request):
 lResume = []
 oauth = get_oauth()
 r = requests.get(url="https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=UserNickname&count=8", auth=oauth)
 lTweets = r.json()
 for dTweet in lTweets:
  lResume.append(dTweet['text'])
 return HttpResponse(json.dumps(lResume),mimetype="application/json")

I have included it in the urls.py file, and finally, in my js I have written:

// Twitter feed
 $.ajax({
  url: 'get_recent_tweets',
  type: 'GET',
  datatype:'json',
  success: function(data, textStatus, xhr) {
   var html = '';
   for (var i = 0; i < data.length; i++) {
    html = html +'<li class="latest-tweet"><p>' + data[i] + '</p></li>';
   }
   $('#tweets_container').append(html);
});

And that’s all.

Advertisements

Migrate database structure with django

In this post I will explain how to migrate an existing database (supported by django), to another desired engine, through django.

First of all, we need to create a project, referencing the database we want to migrate. We will call this db ‘old_db’. So, we create the project  with:

python django-admin.py startproject old_db_project

We configure the settings file of our old_db_project in order it uses the db we want to extract the tables from:

DATABASES = {
 'default': { 
  'ENGINE': 'firebird', # Old_db's engine
  'NAME': 'C:/Users/alba/databases/old_db.fb', # Path to database 
  'USER': 'user',
  'PASSWORD': 'password',
  'HOST': '192.168.0.2',   # Host where the database is located
  'PORT': '3306',     
  'OPTIONS': {'charset':'ISO8859_1'} # DB encoding  (latin-1 in my case)
}}

From the project folder, we execute:

python manage.py inspectdb > old_db_models.py

Now, we have to create a new project, in which we will migrate the database.

python django-admin.py startproject new_db_project

With mysql, in out sql server, create the new_db. For example, through the command line:

mysql -u user -p # You will be asked for the password and prompted to MySql command line
CREATE DATABASE new_db;

Or you can do it from a MySql GUI tool, or whatever.

Modify the new project settings in the next way:

DATABASES = {
 'default': { 
  'ENGINE': 'django.db.backends.mysql', # Old_db's engine
  'NAME': 'C:/Users/alba/databases/new_db.sql', # Path to database 
  'USER': 'user',
  'PASSWORD': 'password',
  'HOST': '192.168.0.2',   # Host where the database is located
  'PORT': '3306',     
}}

Create a new application inside the new project.

python manage.py startapp new_db_app

In the end, we copy the old_db_models.py we obtained before in our new app models.py file, and execute:

python manage.py syncdb

The database structure will be now replicated in our new_db.sql database.

Install Django on Fedora 16

1- Install all the tools we need, if we have not installed them yet:

sudo yum install python django httpd mod_wsgi

2- Start a django project somewhere. For example, in /var/www, I have created a “django” folder. Inside my django folder, I have created my django project, that is called “mysite”:

python django_admin.py startproject mysite

Note: if you do not find django_admin.py, it is located in the bin folder of django install dir (/usr/lib/python2.7/site-packages/django/bin in my case).

A django project folder structure will be automatically created in /var/www/django/mysite.

3- In /var/www/django/mysite we can create an “apache” folder, in which we will store the wsgi handler creation code. Wsgi is an Apache module which allows it to understand our python apps. In this apache folder, we will create a file with the next python code (it does not matter how the file is called):

import os, sys

sys.path.insert(0, '/var/www/django')  # Our project base dir
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'  # Settings is our django project config file, in which we will set the database, the installed apps, etc.

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

In my case I have called the file django.wsgi. So, at this point, we have:

/var/www/django/mysite # Our project path
/var/www/django/mysite/apache/django.wsgi # Our script with wsgi handler creation code

4- Check permissions

chmod 775  /var/www/django
chmod 775  /var/www/django/mysite
chmod 775 /var/www/django/mysite/apache
chmod 664 /var/www/django/mysite/apache/django.wsgi

5- Configure Apache:

 5.1.- Create file /etc/httpd/conf.d/mysite.conf with:

<VirtualHost *:80>
 ServerName mysite
 DocumentRoot /var/www/django/mysite

 WSGIScriptAlias / /var/www/django/mysite/apache/django.wsgi

 <Directory /var/www/django/mysite/apache>
  Order deny,allow
  Allow from all
 </Directory>
</VirtualHost>
In this file we are:
  • Indicating to Apache where is the site to serve (DocumentRoot)
  • Indicating to Apache where is the Wsgi script we previously wrote, and giving permissions to the dir in which it is located.

 5.2.- Uncomment in file /etc/httpd/conf/httpd.conf the next line. This is done to allow virtual hosts:

NameVirtualHost *:80

 5.3.- Add our site to /etc/hosts:

127.0.0.1 mysite

6- Start/Restart apache:

sudo /etc/init.d/http restart

7- Ingress  http://mysite in a web browser, and the django welcome project page will appear.

Note: if a message of “Forbidden” appears you have to type in a terminal the next command, in order SELinux can allow connections:

setsebool -P httpd_read_user_content=1