Roshan Book

My Tech Notebook

Category Archives: Rest

Python tutorial 8 – Conditional Statement

Advertisements

Django in PHP

This was originally published on http://www.scottgorlin.com/2009/07/embedding-django-in-php/

 

Here’s a quicky I solved while developing this site.  I’m an avid lover of Python and so Django was an obvious framework for this site; however, all the prebuilt goodies like WordPress run in crusty old PHP.  How could I build the custom backends I need without recoding the wheel?
There is a custom TemplateLoader for Django which can read in PHP files or output, seen here and downloadable here.  This ran out of the box for me on Django 1.1 beta (I only had to set PHP_IN_SHELL = False in my settings.py to suppress some header output) but only solves the problem if Django is the primary framework; since this site runs mainly in WordPress I needed another solution.

Enter ModRewrite.  It may be possible to do this entirely within WordPress via $wp_rewrite but I dealt with it directly in my .htaccess file:

AddHandler fcgid-script .fcgi

RewriteEngine On
RewriteBase /

# Static routes
RewriteRule ^(media.*)$ - [L]
RewriteRule ^(adminmedia.*)$ - [L]

# Django stuff
RewriteCond %{REQUEST_URI} !(django.fcgi)
RewriteRule ^(accounts.*)$ /django.fcgi/$1 [L]
RewriteRule ^(photos.*)$ /django.fcgi/$1 [L]
RewriteRule ^(admin.*)$ /django.fcgi/$1 [L]

# From WordPress install
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Options All -Indexes

This, of course, is for Python running through fcgi as required by most shared hosts (Bluehost in my case). A similar solution is likely available via Location and SetHandler tags in an Apache configuration.

All this does now is send my accounts, admin, and photos off to Django.  To actually integrate my photo gallery into WordPress I created a page called ‘photos’ with the permalink http://www.scottgorlin.com/photos, which is the exact url I want my Django app to serve.

Now modify your Django base template system to read the WordPress page instead:

# In some base template
{% extends 'php:loadwp.php' %}
{% block wpwrap %}
My wordpress-wrapped content!
{% endblock %}

# loadwp.php
<?php include('http://scottgorlin.com/index.php?pagename=photos') ?>

I could not get the PHP include to work for the direct url (‘/index.php?…’) but this may be possible with some experimentation. Note that it is important not to use the permalink since that is what we have rerouted through to Django!

Now if you point your browser to the permalink it is handled by Django (and php/WordPress runs in the background), but you still will get the naked PHP page by going through index.php.  All you have to do now is put template code in your WordPress post, ie:

{% block wpwrap %}
{% endblock %}

And you’re done! You can see this in action on my Photos page.

I make no claims about the performance or security of this method, but it’s good enough for my personal site.  Short of using an iframe, the only other method I could derive was using a <?php include(‘djangourl’) ?> within your php code; this works but I couldn’t get user authentication running with this method.

Enjoy!

Installing ruby and rails on ubuntu

$ sudo apt-get install aptitude
Make sure to update once finished.
$ sudo aptitude update
OK now we have aptitude installed on our system and let’s install rvm. There is a shell script already on rvm server for this. To run this script we need git and curl installed on our system.
$ sudo aptitude install build-essential curl git-core
Now install rvm
We need to load rvm every time we start a new session, so let’s add this line to ~/.bashrc
$ echo ‘[[ -s “$HOME/.rvm/scripts/rvm” ]] && source “$HOME/.rvm/scripts/rvm”‘ >> ~/.bashrc
Now close your current shell and open a new shell window session, and run this command. So the rvm will suggest what other packages we need to install for Ruby to work
rvm notes
Here is an list of most wanted packages, simply run this in shell prompt. Make sure to use “sudo” as we need to install them system wide. (some of them have already installed though)
sudo aptitude install build-essential bison openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf
UPDATE: 12-02-2011
In your case the packages suggested by rvm notes command, may be slightly different from one listed above.
Finally install ruby 1.9.x with this command. This will take some time so don’t panic. Once it’s done, we’ll have Ruby 1.9.2 installed.
$ rvm install 1.9.2
To start using ruby we need to enter
$ rvm use 1.9.2
Verify it with
$ ruby -v
ruby 1.9.2p136 (2010-12-25 revision 30365) [i686-linux]
We can also set this as the default ruby version for the user by calling this command. Once executed selected version will become the default ruby version for the user.
rvm –default use 1.9.2
OK now we can install any gem on this ruby version. So let’s install rails 3
gem install rails
Verify your installation
$ rails -v
Rails 3.0.3

Deploying cakephp on hostgator method 2

Source:http://www.balistupa.com/blog/2010/11/how-to-install-cakephp-on-hostgator-shared-hosting/

Another helpful link :http://bakery.cakephp.org/articles/gedm/2009/08/29/installing-cakephp-on-shared-hosting

I just buy new shared hosting account for my new domain on hostgator. I want to install cakephp web application into this hosting. However the local setting or common setting that i used on other hosting is not work on hostgator. After figure out the problem, i found that the hostgator hosting does not allow for changing DOCUMENT ROOT setting.

So after research on cakephp tutorial, which come to setting cakephp on shared hosting and i think this solution also good for production phase. I will mention how i set my cakephp on hostgator

  1. move app, cake, plugins, vendors folder into your hosting root folder. It is user root folder on your hosting
  2. delete .htaccess and index.php on cakephp root folder
  3. move /app/webroot/*.* to /public_html folder
  4. delete empty /app/webroot folder
  5. edit /public_html/index.php to point to the ‘cake’ and ‘app’ directories. For example my public_html path for my domain is /home/myhost/public_html, so i point
    – ROOT to look at /home/myhost
    – APP_DIR to look at /home/myhost/app
    – CAKE_CORE_INCLUDE_PATH to look at /home/myhost/cake
  6. edit this line on /public_html/index.php with your appropriate path
    if (!defined('ROOT')) {
    define('ROOT', DS.'home'.DS.'myhost');
    }

    if (!defined('APP_DIR')) {
    define('APP_DIR', 'app');
    }

    if (!defined('CAKE_CORE_INCLUDE_PATH')) {
    define('CAKE_CORE_INCLUDE_PATH', DS.'home'.DS.'myhost');
    }

  7. The only .htaccess i have on /home/myhost/public_html, the setting for .htaccess look like this
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
    </IfModule>

Deploying cakephp on hostgator

I’m having trouble with uploading my cakePHP project on a shared hosting ( from hostgator ). Here is what I have done: I’ve organized my cake distribution like this:

  • home/user/app
  • home/user/cake/cake
  • home/user/cake/vendors
  • home/user/cake/.htaccess
  • home/user/cake/index.php

    I have taken the content of webroot directory from app and put it in

    • home/user/public_html

    I’ve modified this file home/user/public_html/index.php ( the one that was in app/webroot ) changing these lines like this:

    • define(‘ROOT’, DS.’home’.DS.’user’);
    • define(‘APP_DIR’, ‘app’);
    • define(‘CAKE_CORE_INCLUDE_PATH’, DS.’home’.DS.’user’.DS.’cake’);

    And that’s about it.

    MY PROBLEM IS THE FOLLOWING:

    I have managed to deal with all the problems involved in the default index.php cakePHP page and I have a green and fully functional so to say, project. So when I access my “/”, I get:

    “Your tmp directory is writable.

    The FileEngine is being used for caching. To change the config edit APP/config/core.php

    Your database configuration file is present.

    Cake is able to connect to the database.”

    Now, I’ve created a model-view-controller with a mysql database background (like in the 15 min Blog Tutorial ), but when I’m trying to access some views ( e.g. /posts )…it gives me a blank page ( this worked perfect on my local machine virtual server apache ).

    What configuration am I missing ?

    Thank you.

EDIT: Apparently I had problems with the hosting. My URL was something like:

http://gator111.hostgator.com/~username/

and all I had to do was add an extra line in the webroot .htaccess:

RewriteBase /~username/

Thanks for the support.

Cakephp

Tools

1.Bake Tool :
Use :

a) Baking an application – cake bake application name

b) Database configuration – cake bake db_config

c) Baking Model – cake bake model

d) Baking controller – cake bake controller

e) Baking view – cake bake view

f) Getting the help – cake bake help

2. Controller :

Naming Convention

a) File name – tablename_tablename2_controller.php

b) Class name in file name in camel case like – class TablenameTablename2Controller extends AppController

3. Views

Each controller function will have a separate view. And that view is called inside the layout to generate the page.

Ina controller we use the set() method to send data from your controller to your view.

$this->set(‘color’,’pink’)

Once you’ve set(), the variable can be accesses in your view.

<?php echo $color ?> displays pink

4. Associations

It comes naturally

Relationship Association Type Example
one to one hasOne A user has one profile
one to many hasMany Users in a system can have multiple recipies
many to one belongsTo A recipe belongs to a user
many to many hasAndBelongsToMany Recipes have, and belong to many tags

 

5. Layouts

Any view can have as many layouts as needed

$content_for_layout variable include view for that layout

$title_for_layout has title variable

6. Schema Tool

Uses : adding Columns, Altering Columns,Deleting Columns and Version Control

cake schema generate –fgenerate schema file for all tables with or without model with following options

Overwrite- Overwrite schema.php

Snapshot – increment schema.php

Quit

So when you select Snapshot it generates schema_2.php

Run numbered migration : cake schema run update –s2

Where 2 is the Snapshot number you wish to run

Rebuild the database : cake schema run create

Sql Dump file: cake schema dump filename.sql

 

8. Helper

HTML and FORM are default helper always available

Others helpers are Ajax, Javascript,Pagination

It is reusable between View Template, Layouts and elements

Best is when it is chosen by Controller

To enable a helper in your view

$helpers=array(‘Form’,’Html’,’Javascript’,’Time’);

You can also add helpers from within action

$this->helpers[]=’Time’

To create a custom helper

inside /app/views/helpers

class LinkHelper extends AppHelper{

function link_edit($title,$url){

//create specually formatted link

}

}

9. Element

This is like include file for the website. lives in /app/views/elements/

Filename extention is .ctp

Elements which live in generally are Ads,help boxes,navigational controls,extra menus,forms, and callouts

Calling element inside view or layout

<?php echo $this->element(‘help’); ?>

 

10. CRUD

Create row in table – $this->Post->save($this->data)

Read rows from table – $this->Post->find(‘all’)

Update row in table – $this->Post->save($this->data)

Delete row from table – $this->Post->del($id)

11. Validation

In model

var $validate=array(

‘login’=>array(‘alphaNumeric’=>array(‘rule’=>’alphaNumeric’,’required’=>true,’message’=>’alphabets and numbers only’

)

)

 

12. Behaviour

Shared between models

13. Cakephp_OOP

Placed in /project_name/vendors/directory

14. Component

Shared between controllers

15. Route

Router::connect(

‘/blog/:action/*’,

array(‘controller’=>’posts’,’action’=>’index’)

)

Installing netbeans on ubuntu

The new NETBEANS Distribution for is available in the Form of an .sh file. To install Netbeans IDE follow the steps given below. These instructions have been tried and successfully tested on Ubuntu 10.10 and may also work with other Linux Distributions.

 

If you want to Work With JAVA, then you must have the JAVA Development Kit Installed on your system. To download  JDK click here or install it from Ubuntu Software Center.  Once JDK has been installed, Copy your Netbeans installer file to your Desktop. You can also install this from your Downloads Directory, but it is easy to install from Desktop.

  • Launch Terminal . Applications -> Accessories -> Terminal.
  • Now type in the Following Commands in your Terminal

cd Desktop
sudo chmod +x netbeans-*
sudo ./netbeans-*


Now this should start your NetBeans Installer.

Wait for the Installation to finish. Now you have NetBeans installed on your Machine. For launching NetBeans IDE go to Applications -> Programming ->NetBeans IDE.

To unlock any lock process on ubuntu

Need to show subdomain as url than the directory path

Below is a thread from stackoverflow, where I have asked a question. We did solved it.

Question
I have created a subdomain yesterday as http://www.subdomain.example.com. This has created a directory at the root by the name of subdomain. Now when i open http://www.subdomain.example.com, it gets redirected to http://www.example.com/subdomain. How to keep my url from showing the directory path i.e. in address bar it keep showing http://www.subdomain.example.com , while showing content from the directory subdomain. I have a shared hosting account at hostgator. Thanks for the help

Answer

In your .htaccess file, turn off the redirect and use mod_rewrite:

RewriteEngine On RewriteCond %{HTTP_HOST} ^(www.)?subdomain.example.com$ RewriteCond %{REQUEST_URI} !^/subdomain RewriteRule ^(.*)$ /subdomain/$1 [L] 

This checks if the requested host is either http://www.subdomain.example.com orsubdomain.example.com makes sure the request doesn’t already start with a /subdomain and appends it otherwise. This redirects internally on the server so your browser doesn’t actually get redirected (address bar will still say: subdomain.example.com).

 

Answer

Just solved the problem, code given by jon is correct. i was trying to upload .htaccess file to root while i should have uploaded to the subdomain directory. One little edit i did to jon code was on line 3rd . I gave full path to the directory . so the 3rd line of the code looked like RewriteContd %{REQUEST_URI)} http://www.example.com/subdomain

Hide .php extension with url rewriting using .htaccess

This post was originally published at http://roshanbh.com.np/2008/02/hide-php-url-rewriting-htaccess.html
Last time I’ve written an article about hiding php file extension where I’ve showed you how you can use .html or .asp extension of file instead of .php extension. But there was one flaw in that technique you have had to change the file extension explicitly but in this post I’m going to show you how to rewrite the URL instead of renaming the file extension Using this technique you will see product.html in the address bar of the browser but the actual file name remains product.php and you don’t need to rename the file extension. Furthermore you can rewrite the URL like product.php?id=5 to product-5.html.
what is the benefits of rewriting URL?
When a search engine visits the dynamic url like product.php?id=5 it does not give much importance to that URL as search engine sees “?” sign treat it as a url which keeps on changing. so we’re converting the dynamic URL like the product.php?id=5 to static url format like product-5.html. We’ll rewrite the url in such a way that in browser’s address bar it will display as a product-5.html but it actually calls the file product.php?id=5. So that why these kind of URL also named as SEO friendly URL.
what is required for URL rewriting ??
To rewrite the URL you must have the mod_rewrite module must be loaded in apache server. And furthermore, FollowSymLinks options also need to be enabled otherwise you may encounter 500 Internal Sever Error. If you don’t know much about mod_rewrite module then please check this post to know how to check and enable mod_rewrite module in apache?
Examples of url rewriting for seo friendly URL
For rewriting the URL, you should create a .htaccess file in the root folder of your web directory. And have to put the following codes as your requirement.
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*).htm$ $1.php [nc]
The following example will rewrite the test.php to test.html i.e when a URL like http://localhost/test.htm is called in address bar it calls the file test.php. As you can see the regular expression in first part of the RewriteRule command and $1 represents the first regular expression of the part of the RewriteRule and [nc] means not case sensitive.
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^product-([0-9]+).html$ products.php?id=$1
The following example will rewrite the product.php?id=5 to porduct-5.html i.e when a URL like http://localhost/product-5.html calls product.php?id=5 automatically.

%d bloggers like this: