Skip to main content

Important view.py file for using restful api django

from django.shortcuts import render
from django.conf import settings
import requests
from github import Github, GithubException
from .forms import DictionaryForm
def home(request):
is_cached = ('geodata' in request.session)
if not is_cached:
ip_address = request.META.get('HTTP_X_FORWARDED_FOR', '')
params = {'access_key': settings.IPSTACK_API_KEY}
response = requests.get('http://api.ipstack.com/%s' % ip_address, params=params)
request.session['geodata'] = response.json()
geodata = request.session['geodata']
return render(request, 'core/home.html', {
'ip': geodata.get('ip'),
'country': geodata.get('country_name', ''),
'latitude': geodata.get('latitude', ''),
'longitude': geodata.get('longitude', ''),
'api_key': settings.GOOGLE_MAPS_API_KEY,
'is_cached': is_cached
})
def github(request):
search_result = {}
if 'username' in request.GET:
username = request.GET['username']
url = 'https://api.github.com/users/%s' % username
response = requests.get(url)
search_was_successful = (response.status_code == 200) # 200 = SUCCESS
search_result = response.json()
search_result['success'] = search_was_successful
search_result['rate'] = {
'limit': response.headers['X-RateLimit-Limit'],
'remaining': response.headers['X-RateLimit-Remaining'],
}
return render(request, 'core/github.html', {'search_result': search_result})
def github_client(request):
search_result = {}
if 'username' in request.GET:
username = request.GET['username']
client = Github()
try:
user = client.get_user(username)
search_result['name'] = user.name
search_result['login'] = user.login
search_result['public_repos'] = user.public_repos
search_result['success'] = True
except GithubException as ge:
search_result['message'] = ge.data['message']
search_result['success'] = False
rate_limit = client.get_rate_limit()
search_result['rate'] = {
'limit': rate_limit.rate.limit,
'remaining': rate_limit.rate.remaining,
}
return render(request, 'core/github.html', {'search_result': search_result})
def oxford(request):
search_result = {}
if 'word' in request.GET:
form = DictionaryForm(request.GET)
if form.is_valid():
search_result = form.search()
else:
form = DictionaryForm()
return render(request, 'core/oxford.html', {'form': form, 'search_result': search_result}) Important Html
{% extends 'base.html' %}
{% block content %}
<h2>GitHub API</h2>
<form method="get">
<input type="text" name="username">
<button type="submit">search on github</button>
</form>
{% if search_result %}
{% if search_result.success %}
<p>
<strong>{{ search_result.name|default_if_none:search_result.login }}</strong> has
<strong>{{ search_result.public_repos }}</strong> public repositories.
</p>
{% else %}
<p><em>{{ search_result.message }}</em></p>
{% endif %}
<p>Rate limit: {{ search_result.rate.remaining }}/{{ search_result.rate.limit }}</p>
{% endif %}
{% endblock %}

Comments

Popular posts from this blog

GitHub Push (exact method)

  Open Terminal . Change the current working directory to your local project. Initialize the local directory as a Git repository. $ git init Add the files in your new local repository. This stages them for the first commit. $ git add . # Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE '. Commit the files that you've staged in your local repository. $ git commit -m "First commit" # Commits the tracked changes and prepares them to be pushed to a remote repo   Update Git ------------------ $ git remote add upstream https://github.com/siumhossain/Personal-Blog.git $ git pull upstream master $ git status $ git push origin master 😤 Ignore sensitive information. $touch .gitignore and add file or folder name for ignore those from uploading those file in repo  

Data visualize with matplotlib(solid line)

Nominal GDP      from matplotlib import pyplot as plt      years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]      gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]      plt.title('GDP')      plt.ylabel('Billios of $')      plt.plot(years,gdp,color='red',marker='o',linestyle='solid')      plt.show() * plt.plot(x,y,color,marker per year,linestyle) there are several line style '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted' fig-

Form basic django

Model.py ----------------------------- from django.db import models # Create your models here. class Contact(models.Model):     name = models.CharField(max_length = 100)     email = models.CharField(max_length = 100)     phone = models.IntegerField()     message = models.CharField(max_length = 1000)     def __str__(self):         return self.name views.py ----------------------------------- from django.shortcuts import render,redirect from django.http import HttpResponse from . forms import ContactForm from . models import Contact # Create your views here. def index(request):     return render(request,'index.html') def contact(request):     if request.method == "POST":         form = ContactForm(request.POST or None)         if form.is_valid():       ...