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

February 17, 2015

Using django as a microframework, like flask.

February 17, 2015 0
Today me and my friend were discussing about the flask and django. We were arguing over flask is microframework and django is not and all other topics related to pros and cons.
I'm not going to start comparing these two great frameworks, but I've created a django-microsite project for a test.
I break down the settings.py, urls.py, views.py in one file. I googled about all these and finally achieved it.
Below is sample code. filename : django-microsite.py
Requirement : Django Framework and Python

#########################################
# A Pythonic Django Microsite example
# Inspired by Flask and Bottle framework
#########################################


import sys
from django.conf import settings

settings.configure(
 DEBUG=True,
 SECRET_KEU='secretkeygoeshere',
 ROOT_URLCONF = __name__,
 MIDDLEWARE_CLASSES = (
     'django.middleware.common.CommonMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
 ),
)

from django.conf.urls import url
from django.http import HttpResponse
from django.shortcuts import render_to_response

def index(request):
 return HttpResponse("Hey see this! It's working.")

urlpatterns = ( 
 url(r'^$', index,name="index_page"),
)

if __name__ == "__main__":
 from django.core.management import execute_from_command_line
 execute_from_command_line(sys.argv)


You will think, how to run this ? It's a django project :) use runserver command.
python django-microsite.py runserver
you can find the code on https://github.com/ashish2py/django-microsite.
for configuration, please read the following doc django-configurations

I'll explain about the codes later by updating the same blogpost.
Read more...

June 26, 2014

Alternative of google-map API, making request more than 2500.

June 26, 2014 0
I was looking for a free api which can help me to get latitude/longitude on the basis of Postcode.

I tested pygeocoder and other api librearies which can help me, but none of them allowed me to query more than 25,000/day cause everyone is belongs to Google.

So I did an old school coding by using Mechanize and BeautifulSoup.
I used http://services.gisgraphy.com/public/geocoding.html. It's a free, I think they are providing 30,000 requests for demo user, I didn't tested 30,000 requests cause I've 29,000 records to generate lat/long. I don't want to waste my hits for a day. I'll test and update here.

Code is not clean, cause it's a test.

Keep Coding .


import mechanize
from bs4 import BeautifulSoup 

for x in xrange(30000):

    print '----------------- searching ---------------'
    br = mechanize.Browser()
    br.open("http://services.gisgraphy.com/public/geocoding.html")
    
    add = '81100'
    con='Malaysia'
    
    br.select_form(nr=0)
    
    br.form["address"] = add
    for i in range(0, len(br.find_control(type="checkbox").items)):
        br.find_control(type="checkbox").items[i].selected =True
    br.form["country"]=["MY"]
    
    print 'hitting --- ',x
    response = br.submit()
    soup = BeautifulSoup(response)
    
    
    links = soup.find_all('li')
    print '--------- getting list ----------'
    
    li = soup.find('div', {'class': 'summary'})
    
    print '---------- looking for latitude and longitude -------------'
    list= []
    children = li.findChildren()
    for child in children:
        list.append(str(child))

    print ' found latitude and longitude at point -->  ',x
    
    latitude = list[0]
    longitude = list[1]
    
    lat = latitude[9+5:len(latitude)-5].split()
    lng = longitude[9+6:len(longitude)-5].split()
    
    print str(lat).replace(',','.')
    print str(lng).replace(',','.')

#for f in br.forms():
#    print f



Source Code : https://bitbucket.org/ashish2py/quickhack/



Read more...

July 31, 2013

Sending Email : Django Terminal Test.

July 31, 2013 1

While I was making contact-us form in PHP for my client then I thought about to do same in Djago-Python. Target was to get the form input and email it. Here I'm going to test only the DjangoEmail module using shell.
Edit settings.py with code below:
    #settings for django email( writing for gmail)
    EMAIL_USE_TLS = True
    EMAIL_HOST = 'smtp.gmail.com'
    SITE_HOST = '127.0.0.1:8000'
    DEFAULT_FROM_EMAIL ='Dotorbit Team '
    EMAIL_PORT = 587
    EMAIL_HOST_USER = 'dotorbit.dev@gmail.com'
    EMAIL_HOST_PASSWORD = 'your-password'
    #Run interactive mode, 
    python manage.py shell
    #Import the EmailMessage module,
    >>>from django.core.mail import EmailMessage
    #Send the email,
    >>>email = EmailMessage('Subject goes here ', ' Body goes here ', to=['reciever@email.com'])
    >>>email.send()
    >>>1

This will return 1, means everything is working fine. form and view, I'll write in next post.
Read more...

April 29, 2012

send tweets from pythom , using python-twitter ...simple way ( 5 steps )

April 29, 2012 0
Today morning around 4am , when I was designing my codeleaf blog site I just thought of tweeting something interesting but I dont wanted to tweet from the twitter Page. Instead, I wanted to tweet from terminal where I was doing other programming stuffs... So I decided to write a python-script to Post a tweet from my Terminal .
So I googled about "tweet from python" and I came across python-twitter and I started following Wiki for implementing that thing .
Steps that need to be followed are as follows ::
1. Register an Application on Twitter Dev-Center
Set your application's "Access level : Read, write, and direct messages "
Otherwise you will get an error for "Access level : Read Only"(TwitterError: Read-only application cannot POST.)

2. Copy your
 consumer_key = 'consumer_key',
 consumer_secret = 'consumer_secret',
 access_token_key = 'access_token_key',
 access_token_secret = 'access_token_secret'
and paste on some TextEditor ,because we will use this later .
3. Installation ( Python-Twitter )

Install the dependencies:
If your python-version > python2.7.2 , then skip first two library and directly install the third-one(python-oauth2) .
Download the latest python-twitter library from:
Extract the source distribution and run:
 $ python setup.py build
   $ python setup.py install
 

4 . create a python file and write the below code on it .

  
 import twitter
 api  = twitter.Api()

 #tweet
 def tweet(tweet_status):
  status = api.PostUpdate(tweet_status)
  print "Posted successfully"
  print status.text

 # OAuth authentication
 api = twitter.Api(
  consumer_key = 'consumer_key',
  consumer_secret = 'consumer_secret',
  access_token_key = 'access_token_key',
  access_token_secret = 'access_token_secret'
 )

 tweet_status = raw_input("Tweet Status : ")
 tweet(tweet_status)

5. Thats it . Now run the script , and Terminal(command prompt) will ask you to enter your "Tweet" .

 $ python pytweet.py 
   Tweet Status : I love Python-Twitter .
   Posted successfully
 Tweet Status : I love Python-Twitter .

Read more...

May 17, 2010

Django-Python Web Framework

May 17, 2010 0
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.

Developed four years ago by a fast-moving online-news operation, Django was designed to handle two challenges: the intensive deadlines of a newsroom and the stringent requirements of the experienced Web developers who wrote it. It lets you build high-performing, elegant Web applications quickly.

Read more about django from
Django Web Framework

Django focuses on automating as much as possible and adhering to the DRY principle.
Now Django 1.2 is release.

Download django from here,
Django 1.2 download
Read more...

Follow Us @soratemplates