Friday 27 November 2015

Configuring Django with uWSGI + NGINX Server

Before you start setting up uWSGI :
 

1. Make sure you are in a virtualenv for the software we need to install.Create Virtualenv like this:
       
        virtualenv uwsgi-tutorial
        cd uwsgi-tutorial
        source bin/activate

2. Install Django into your virtualenv, create a new project, and cd into the project:
       
      pip install Django
      django-admin.py startproject mysite
      cd mysite
       
 <-- Basic uWSGI installation and configuration -->
    

3. Install uWSGI into your virtualenv:
       pip install uwsgi
       
4. Create a file called test.py for testing and place the code in it:
     # test.py
     def application(env, start_response):
        start_response('200 OK', [('Content-Type','text/html')])
        return [b"Hello World"] # python3
        #return ["Hello World"] # python2
   
5. Now test and run the uWSGI:
      uwsgi --http :8000 --wsgi-file test.py
       
6. Now we want uWSGI to do the same thing, but to run a Django site instead of the test.py module:
 

If your project is running with pyhton manage.py runserver:8000 then,Run it with uWSGI
      uwsgi --http :8000 --module mysite.wsgi
        

Point your browser at the server; if the site appears, it means uWSGI is able to serve your Django application from your virtualenv, and this stack operates correctly
   
<-- Basic nginx installation -->
   
7. Install and start nginx:
      sudo apt-get install nginx
      sudo /etc/init.d/nginx start    # start nginx
       
Note: To restart nginx just use sudo /etc/init.d/nginx restart command.
        

And now check that the nginx is serving by visiting it in a web browser on port 80 - you should get a message from nginx:          
    “Welcome to nginx!”. 

That means these components of the full stack are working together.
   
<-- Configure nginx for your site -->
   
8. You will need the uwsgi_params file, which is available in the nginx directory of the uWSGI distribution, or from https://github.com/nginx/nginx/blob/master/conf/uwsgi_params

Copy it into your project directory. In a moment we will tell nginx to refer to it.
   
9. Now create a file called mysite_nginx.conf at
/etc/nginx/sites-available/, using the following command:

   sudo nano /etc/nginx/sites-available/mysite_nginx.conf

and paste the following code in it:
 
      # mysite_nginx.conf

      # the upstream component nginx needs to connect to
      upstream django {
       # server unix:///path/to/your/mysite/mysite.sock; # for a file socket
        server 127.0.0.1:8001; # for a web port socket (we'll use this first)
            }

       # configuration of the server
       server {
         # the port your site will be served on
         listen      8000;
         # the domain name it will serve for
       server_name 127.0.0.1; # substitute your machine's IP address or FQDN
         charset     utf-8;

         # max upload size
         client_max_body_size 75M;   # adjust to taste

         # Django media
         location /media  {
          alias /path/to/your/mysite/media;# your Django project's media files - amend as required
                }

         location /static {
             alias /path/to/your/mysite/static; # your Django project's static files - amend as required
                }

       # Finally, send all non-media requests to the Django server.
         location / {
           uwsgi_pass  django;
         include     /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed
                }
            } 

Note: Replace project paths acoordingly.Copy and paste this file in your project directory as well.
    

10. Now symlink to this file from /etc/nginx/sites-enabled so nginx can see it.
 

sudo ln -s /etc/nginx/sites-available/mysite_nginx.conf /etc/nginx/sites-enabled/
   
11. Before running nginx, you have to collect all Django static files in the static folder. First of all you have to edit mysite/settings.py adding:
 

  STATIC_URL = '/static/'
  STATIC_ROOT = os.path.join(BASE_DIR, "static/")

  MEDIA_ROOT = os.path.join(BASE_DIR, "media/")

  MEDIA_URL = '/media/'


and then run 'python manage.py collectstatic'.

Check the configuration syntax by typing:

  sudo service nginx configtest
Now restart the nginx 'sudo /etc/init.d/nginx restart'.
    
To check that media files are being served correctly, add an image called media.png to the /path/to/your/project/project/media directory, then visit http://example.com:8000/media/media.png - if this works, you’ll know at least that nginx is serving files correctly.

Note: If you face an error then check the nginx error log at "/var/log/nginx/error.log". If there is a permission denied error then it means your media folder doesn't have permissions for accessing. Make your media folder and its content accessible by giving it valid permissions.
   
12. Let’s get nginx to speak to the “hello world” test.py application.
           
   uwsgi --socket :8001 --wsgi-file test.py
       
   Visit: http://127.0.0.1:8000/
        

13. Using Unix sockets instead of ports:   
Edit mysite_nginx.conf, changing it to match:
            
  server unix:///path/to/your/mysite/mysite.sock; # for a file socket
  # server 127.0.0.1:8001; # for a web port socket (we'll use this first)
       
and restart nginx.

Run uWSGI again:
           
    uwsgi --socket mysite.sock --wsgi-file test.py


Try http://127.0.0.1:8000/ in the browser.If that doesn’t work.
check your nginx error log(/var/log/nginx/error.log). If you see something like:
  

connect() to unix:///path/to/your/mysite/mysite.sock failed (13: Permission denied)
        

then probably you need to manage the permissions on the socket so that nginx is allowed to use it.
       
Try uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=666 # (very permissive)
       
Now refresh the browser again.
       
If it works then you are doing good so far!
   
14. Running the Django application with uwsgi and nginx
       
Let’s run our Django application:
           
uwsgi --socket mysite.sock --module mysite.wsgi --chmod-socket=666

Now uWSGI and nginx should be serving up not just a “Hello World” module, but your Django project.
       
15. Configuring uWSGI to run with a .ini file
       
Create a file called 'mysite_uwsgi.ini' at /etc/uwsgi/sites using these commands:


  sudo mkdir -p /etc/uwsgi/sites
  cd /etc/uwsgi/sites
  sudo nano mysite_uwsgi.ini

and paste the following code in it: 
      
              # mysite_uwsgi.ini file
              [uwsgi]
 

              # Django-related settings
              # the base directory (full path)
              chdir           = /path/to/your/project
              # Django's wsgi file
              module          = mysite.wsgi
              # the virtualenv (full path)
              home            = /path/to/virtualenv
 

              # process-related settings
              # master
              master          = true
              # maximum number of worker processes
              processes       = 10
              # the socket (use the full path to be safe
              socket          = /path/to/your/project/mysite.sock
              # ... with appropriate permissions - may be needed
              chmod-socket    = 666
              # clear environment on exit
              vacuum          = true
           
Note: Change paths accordingly.
Also Copy this file in your project directory.We will use this to run the our project manually from the terimanl.
        

Afer placing the above code, run uswgi using this file:
           
uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file
       
Once again, test that the Django site works as expected.
   
16. Install uWSGI system-wide
So far, uWSGI is only installed in our virtualenv; we’ll need it installed system-wide for deployment purposes.

Deactivate your virtualenv by typing following command in terminal:       
 

   deactivate

and install uWSGI system-wide:
           
   sudo pip install uwsgi
       
Check again that you can still run uWSGI just like you did before:
           
   uwsgi --ini mysite_uwsgi.ini
 

17. Now create a upstart script for uWsgi:
We will create an Upstart script in the /etc/init directory, where these files are checked:

   sudo nano /etc/init/uwsgi.conf

and place the following code in it:
  description "uWSGI application server in Emperor mode"
   
  start on runlevel [2345]
  stop on runlevel [!2345]
  
  setuid user
  setgid www-data 
  exec /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites 

Note: Replace user with your username.

Start the uWSGI server using
  sudo service uwsgi start
Now point to the browser and check your running site.               
If it works then here's your happy moment :)

Thursday 10 September 2015

OAuth2 setup in restapi and authentication with api

OAuth2 setup in restapi and authentication with api 

Firstly setup the restframework
After setup please follow these steps

1.pip install django-oauth-toolkit

2.add ‘oauth2_provider’ to your INSTALLED_APPS setting.

3.url(r'^o/', include('oauth2_provider.urls')), to your urls.py

4.Add the following to your settings.py module:

    OAUTH2_PROVIDER = {
        # this is the list of available scopes
        'SCOPES': ['read', 'write', 'groups']
    }

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        ),
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        )
    }

5.Run python manage.py syncdb

6.open backend admin (127.0.0.1:8000/admin)

7.Step 3: Register an application

    To obtain a valid access_token first we must register an application.

    From the admin go to oauth2_provider > applications > Add Application. Fill the form with the following data:

        User: your current user
        Client Type: confidential
        Authorization Grant Type: Resource owner password-based
       
    Save your app!

8.Get your token and use your API

At this point we’re ready to request an access_token. Open your shell
    Note = TO get client id and client secret, go to the admin panel and then oauth2_provider > applications >select application
   
    syntax = curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" http://<client_id>:<client_secret>@localhost:8000/o/token/
   
    eg. =  curl -X POST -d "grant_type=password&username=admin&password=admin" http://lh4RIKR2Cn95LHVOYLMddT1RAxDgHRDIEwPyR61g:82aVoSzfHyoWEguSBhp4ZHXigowzuLJS45kI7j3l6Flz5k42LDcBHiKSTl0fJ5OhijtIxY2sNPUDihKSQKna1eaEXt3dTG69u3eLNq6EJqqJdGfJRgnzFSSaHPU2NVqT@192.168.1.6:8000/shopping/o/token/

Response should be something like:

    {
        “access_token”: “<your_access_token>”, “token_type”: “Bearer”, “expires_in”: 36000, “refresh_token”: “<your_refresh_token>”, “scope”: “read write groups”

    }
   
   
Authentication with api from front end

    def userlogin(request):
        url = 'http://192.168.1.6:8000/shopping/o/token/'
        form = LoginForm
        template_name = 'index.html'
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            cd = {}
            cd['username'] = username
            cd['password'] = password
            cd['client_id'] = 'lh4RIKR2Cn95LHVOYLMddT1RAxDgHRDIEwPyR61g'
            cd['client_secret'] = '82aVoSzfHyoWEguSBhp4ZHXigowzuLJS45kI7j3l6Flz5k42LDcBHiKSTl0fJ5OhijtIxY2sNPUDihKSQKna1eaEXt3dTG69u3eLNq6EJqqJdGfJRgnzFSSaHPU2NVqT'
            cd['grant_type'] = 'password'
           
            r = requests.post(url, data=cd)       
            if r:
                data = r.json()
                token = data['access_token']
                request.session['token'] = 'Bearer ' + token
                headers = {'Authorization': request.session['token']}
                s = requests.get('http://192.168.1.6:8000/shopping/registration/', headers=headers)
               
                data2  = s.json()
                for d in data2:
                    if d['username'] == username:
                        print username
                        return HttpResponse("Working") 

Monday 7 September 2015

Reset password/Forgot password/Lost password in django

To recover your lost password in Django we have the following steps i am following the steps from Here- First we should also know that how does this works-
  1. On clicking Forgot/Lost Password link on your template it'll redirect to a page where you have to enter your registered user email id.
  2. If email id is valid it'll send an email with a update password link.
  3. On clicking that link you have to submit your new password twice.
  4. On successful password update  it'll redirect with Log-in link.


STEP 1:- Before begin anything consider we have setup our project like there is a project and an app, and copy the required template from Django's core template to your own project template system, copy this whole registration folder into our template. we can copy the folder from-
"Our_project/lib/python2.7/site-packages/django/contrib/admin/templates/registration".


It'll contain following files-


/django/contrib/admin/templates/registration/password_reset_form.html
/django/contrib/admin/templates/registration/password_reset_done.html
/django/contrib/admin/templates/registration/password_reset_confirm.html
/django/contrib/admin/templates/registration/password_reset_complete.html
/django/contrib/admin/templates/registration/password_reset_email.html
 

STEP 2 :- setting.py:- Configure the smtp/mail server in setting.py

if DEBUG:
    EMAIL_HOST = 'localhost'
    EMAIL_PORT = 1025
    EMAIL_HOST_USER = ''
    EMAIL_HOST_PASSWORD = ''
    EMAIL_USE_TLS = False
    DEFAULT_FROM_EMAIL = 'testing@example.com'


This is the default server of the local host, To activate this we have to run a command i.e.
"python -m smtpd -n -c DebuggingServer localhost:1025"

Beside this we can add server detail as same as below:-

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'username@gmail.com'
EMAIL_HOST_PASSWORD = 'gmailPassword'
DEFAULT_FROM_EMAIL = 'username@gmail.com'
DEFAULT_TO_EMAIL = 'username@gmail.com'

<!-- OR -->
EMAIL_HOST = 'mail.xyz.com'
EMAIL_HOST_USER = 'username@xyz.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 25
EMAIL_USE_TLS = False


STEP 3:- Give URL to your html for lost password link as below-

<a class="to_forget" href="{% url 'password_reset' %}">Lost your password?</a>
STEP 4:- Add Few URLs in your main project.url.py as below
   
url(r'^user/password/reset/$', 'django.contrib.auth.views.password_reset', {'post_reset_redirect' : '/user/password/reset/done/'}, name="password_reset"),
url(r'^user/password/reset/done/$', 'django.contrib.auth.views.password_reset_done'),
url(r'^user/password/reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm', {'post_reset_redirect' : '/user/password/done/'}),
url(r'^user/password/done/$', 'django.contrib.auth.views.password_reset_complete'),


STEP 5:- Now in template/registration/Password_reset_email.html
replace {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
with    {{ domain }}{% url 'django.contrib.auth.views.password_reset_confirm' uidb64=uid token=token %}

Now we're able to update our lost password,
in the last we can change template/registration/password_reset_complete.html with our login link.

Wednesday 24 June 2015

How to configure Mezzanine with MySql and wsgi ?

1. Firstly write these commands on terminal

    1.sudo mkdir /var/www/lyfstyle/
    2.sudo mkdir /var/www/lyfstyle/apache

2. sudo vi /var/www/lyfstyle/apache/apache.wsgi
    --Paste this code in apache.wsgi--

    import os
    import sys
   
    path = '/var/www'
    if path not in sys.path:
        sys.path.insert(0, '/var/www/lyfstyle')
        sys.path.append('/var/www/lyfstyle/lyfstyle_env/mezzanine_lyfstyle')
   
    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
   
    import django.core.handlers.wsgi
    application = django.core.handlers.wsgi.WSGIHandler()

OR 

import os
import sys

path = '/var/www/lyfstyle'

if path not in sys.path:
    sys.path.insert(0, '/var/www/lyfstyle/mezzanine_lyfstyle')
    sys.path.append('/var/www/lyfstyle')

os.environ['DJANGO_SETTINGS_MODULE'] = 'mezzanine_lyfstyle.settings'

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

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


3. Open .conf file by this command ('sudo nano /etc/apache2/sites-available/000-default.conf')
    #And Paste this code   

    listen 8080
    <virtualHost *:8080>
        ServerName dev.lyfstyle
        DocumentRoot /var/www/lyfstyle/mezzanine_lyfstyle
   
        AliasMatch ^/([^/]*\.css) /var/www/lyfstyle/mezzanine_lyfstyle/static/css/
       # create alias for media and static directories
        Alias /media/ /var/www/lyfstyle/mezzanine_lyfs104.236.21.57tyle/media/
        Alias /static/ /var/www/lyfstyle/mezzanine_lyfstyle/static/
   
        <Directory /var/www/lyfstyle/mezzanine_lyfstyle/static>
            Order deny,allow
            Allow from all
        </Directory>
   
        <Directory /var/www/lyfstyle/lyfstyle_env/mezzanine_lyfstyle/media>
            Order deny,allow
            Allow from all
        </Directory>
   
        <Directory /var/www/lyfstyle/mezzanine_lyfstyle>
            Order allow,deny
            Allow from all
        </Directory>
   
        WSGIDaemonProcess mysite.local processes=2 threads=15 display-name=%{GROUP}
        WSGIProcessGroup mysite.local
   
        WSGIScriptAlias /  /var/www/lyfstyle/apache/apache.wsgi
   
    </VirtualHost>

4.After run this command:
   a. sudo a2enmod wsgi


5.  After create Project:
    a. mezzanine-project mezzanine_lyfstyle
    b. cd mezzanine_lyfstyle
    c. python manage.py syncdb
    d. python manage.py collecttemplates
    e. python manage.py collectstatic

6. If you want to change Database like Mysql, sqlite, etc,
   a. open mezzanine_lyfstyle (folder)
   b. open local_settings.py
   c. Than replace this line
      ENGINE": "django.db.backends.sqlite3"
      by
      ENGINE": "django.db.backends.mysql"
     
      And Enter these Settings
     
      NAME: "DBName create in phpmyadmin",
   
      USER: "Username of phpmyadmin",
   
      PASSWORD: "Password of phpmyadmin",


Wednesday 18 February 2015

How to configure Flask with WSGI ?

# Configure Flask with WSGI

1.Install and Enable mod_wsgi

sudo apt-get install libapache2-mod-wsgi python-dev

#To enable mod_wsgi, run the following command: 
sudo a2enmod wsgi  

2. Creating a Flask App

a. cd /var/www 
b. sudo mkdir FlaskApp
c. cd FlaskApp
d. sudo mkdir FlaskApp
e .cd FlaskApp
f .sudo mkdir static templates    
 

3.Now, create the __init__.py file that will contain the flask application logic.

sudo nano __init__.py 
 
#Add following logic to the file:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
    return "Hello, I love Digital Ocean!"
if __name__ == "__main__":
    app.run() 

4.Configure and Enable a New Virtual Host

sudo nano /etc/apache2/sites-available/FlaskApp (for older ubuntu version)
sudo nano /etc/apache2/sites-available/FlaskApp.conf (for 13+ ubuntu version) 

#Add the following lines of code to the file to configure the virtual host.
<VirtualHost *:8080>
  ServerName localhost
  ServerAdmin admin@mywebsite.com
  WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
  <Directory /var/www/FlaskApp/FlaskApp/>
   Order allow,deny
   Allow from all
  </Directory>
  Alias /static /var/www/FlaskApp/FlaskApp/static
  <Directory /var/www/FlaskApp/FlaskApp/static/>
   Order allow,deny
   Allow from all
  </Directory>
  ErrorLog ${APACHE_LOG_DIR}/error.log
  LogLevel warn
  CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost> 
 
Note :- Define LISTEN port before VirtualHost

Save and close the file.

5.Enable the virtual host with the following command:

sudo a2ensite FlaskApp
 

 6.Create the .wsgi File

cd /var/www/FlaskApp
sudo nano flaskapp.wsgi 
 
Add the following lines of code to the flaskapp.wsgi file:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")

from FlaskApp import app as application
application.secret_key = '123456789' 

Save and close the file.


Now your directory structure should look like this:

|--------FlaskApp
|----------------FlaskApp
|-----------------------static
|-----------------------templates
|-----------------------__init__.py
|----------------flaskapp.wsgi
 

7.Than Restart the apache server following this command

sudo service apache2 restart