
You need to create a file named .gitattributes in the root folder of my repository.
Use this source code to tell GitHub is a python project:
* linguist-vendored
*.py linguist-vendored=false
Now the project will be target with python language.
Is a blog about python programming language. You can see my work with python programming language, tutorials and news.
* linguist-vendored
*.py linguist-vendored=false
Now the project will be target with python language.
[mythcat@desk django]$ source env/bin/activate
I update my django version 3.0 up to 3.0.1.(env) [mythcat@desk django]$ pip3 install --upgrade django --user
Collecting django
...
Successfully uninstalled Django-3.0
Successfully installed django-3.0.1
The next step comes with installation of Python modules for Django and Django REST:(env) [mythcat@desk django]$ pip3 install djangorestframework --user
Collecting djangorestframework
...
Installing collected packages: djangorestframework
Successfully installed djangorestframework-3.11.0
Into my folder mysite I run this commands(env) [mythcat@desk django]$ cd mysite/
(env) [mythcat@desk mysite]$ python3 manage.py makemigrations
No changes detected
(env) [mythcat@desk mysite]$ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, test001
Running migrations:
No migrations to apply.
To pass information over to an HTTP GET request, the information object must be translated into valid response data.(env) [mythcat@desk mysite]$ cd mysite/
(env) [mythcat@desk mysite]$ vim serializers.py
The code for this python script is this:from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
The next changes will be on urls.py and views.py.from django.contrib import admin
from django.urls import path
from test001.views import home_page
from test001.views import Test001ChartView
#
from django.urls import include, path
from rest_framework import routers
from test001 import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
app_name = 'test001'
urlpatterns = [
path('admin/', admin.site.urls),
#path('', home_page, name ='home'),
path('', Test001ChartView.as_view(), name = 'home'),
# Use automatic URL routing
# Can also include login URLs for the browsable API
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
My views.py file is this:from django.http import HttpResponse
from django.shortcuts import render
# snippet
from django.shortcuts import get_object_or_404
# for chart
from django.views.generic import TemplateView
from .models import Test001, Snippet
#
#def home_page(request):
# return HttpResponse('Home page!')
# django framework
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from mysite.serializers import UserSerializer, GroupSerializer
def home_page(request):
return render(request, 'test001/home.html',{
'name':'CGF',
'html_items': ['a','b','c','d','e']
})
# define view for chart
class Test001ChartView(TemplateView):
template_name = 'test001/chart.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["qs"] = Test001.objects.all()
return context
def snippet_detail(request, id):
snippet = get_object_or_404(Snippet, id=id)
return render(request, 'test001/snippets_detail.html', {'snippet': snippet})
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
The settings module for this my project is stored in mysite/settings.py and I add this:INSTALLED_APPS = [
...
'rest_framework',
]
I run the django project and works well:python3 manage.py runserver
The http://127.0.0.1:8000/users/ page come with this output:[mythcat@desk ~]$ pip3 install --upgrade PyQt5 --user
Collecting PyQt5
...
Installing collected packages: PyQt5-sip, PyQt5
Successfully installed PyQt5-5.14.0 PyQt5-sip-12.7.0
Let's see how can see the version:[mythcat@desk ~]$ python3
Python 3.7.5 (default, Dec 15 2019, 17:54:26)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt5.Qt import PYQT_VERSION_STR
>>> print("PyQt version:", PYQT_VERSION_STR)
PyQt version: 5.14.0
[mythcat@desk ~]$ pip3 install google --user
Collecting google
...
Installing collected packages: google
Successfully installed google-2.0.3
This is a simple example for search on web with this words: protv news 2019.Help on function search in module googlesearch:
search(query, tld='com', lang='en', tbs='0', safe='off', num=10, start=0, stop=None,
domains=None, pause=2.0, tpe='', country='', extra_params=None, user_agent=None)
Search the given query string using Google.
:param str query: Query string. Must NOT be url-encoded.
:param str tld: Top level domain.
:param str lang: Language.
:param str tbs: Time limits (i.e "qdr:h" => last hour,
"qdr:d" => last 24 hours, "qdr:m" => last month).
:param str safe: Safe search.
:param int num: Number of results per page.
:param int start: First result to retrieve.
:param int stop: Last result to retrieve.
Use None to keep searching forever.
:param list domains: A list of web domains to constrain
the search.
:param float pause: Lapse to wait between HTTP requests.
A lapse too long will make the search slow, but a lapse too short may
cause Google to block your IP. Your mileage may vary!
:param str tpe: Search type (images, videos, news, shopping, books, apps)
Use the following values {videos: 'vid', images: 'isch',
news: 'nws', shopping: 'shop', books: 'bks', applications: 'app'}
:param str country: Country or region to focus the search on. Similar to
changing the TLD, but does not yield exactly the same results.
Only Google knows why...
:param dict extra_params: A dictionary of extra HTTP GET
parameters, which must be URL encoded. For example if you don't want
Google to filter similar results you can set the extra_params to
{'filter': '0'} which will append '&filter=0' to every query.
:param str user_agent: User agent for the HTTP requests.
Use None for the default.
:rtype: generator of str
:return: Generator (iterator) that yields found URLs.
If the stop parameter is None the iterator will loop forever.
This is the script:[mythcat@desk ~]$ python3
Python 3.7.5 (default, Dec 15 2019, 17:54:26)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from googlesearch import search
>>> query = "protv news 2019"
>>> my_results_list = []
>>> for url in search(query,
... tld = 'com',
... lang = 'en',
... num = 10,
... start = 0,
... stop = None,
... pause = 2.0,):
... my_results_list.append(url)
... print(url)
...
https://stirileprotv.ro/protvnews/
https://stirileprotv.ro/
https://stirileprotv.ro/superbun/protv-news.html
https://www.facebook.com/ProTvNews/
https://www.youtube.com/playlist?list=PLCJaU-QvLGR_FSZw6yeqBJHDe9LgFDRdy
https://www.youtube.com/watch?v=HaiQtDlaNic
https://www.youtube.com/watch?v=hxMEgAANSl4
https://www.youtube.com/channel/UCbbDChpDluLkdnH8QMwN6qA
https://www.youtube.com/watch?v=5zuN9uWFcTE
https://protvplus.ro/tv-live/1-pro-tv
https://en.wikipedia.org/wiki/Pro_TV
https://pro-tv.com/news/page/2/
https://m.youtube.cat/channel/UCbbDChpDluLkdnH8QMwN6qA
...
@csrf_protect
However csrf_protect will check only POST requests.{% csrf_token %}
I can use the token with my code if I want to send it to the website.from django.middleware.csrf import get_token
Then this can be used in view.py with a hidden form field with the name csrfmiddlewaretoken present in all outgoing POST forms.
def my_csrf_form(request):
response = """ ... type = "hidden" name = "csrfmiddlewaretoken" value = "__token__" ... """
This can be used with:token = get_token(request)
response = response.replace('__token__', html.escape(token))
response += dumpdata('POST', request.POST)
return HttpResponse(response)
This will get a token for the current request and fill into value = "__token__".
[mythcat@desk projects]$ source django/env/bin/activate
(env) [mythcat@desk projects]$ ls
cache django kaggle logs OSMnx pygal_ex SantaClaus.py
(env) [mythcat@desk projects]$ cd django/
(env) [mythcat@desk django]$ ls
env mysite venv
(env) [mythcat@desk django]$ cd mysite/
I change the chart.html file with this before javascript script:... {% csrf_token %} ...
You can use it in javascript - jQuery like this, if you want:var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
The CSRF protection on Django on my form can bu used in view.py:...
# use csrf_protect
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
...
# define view for chart
class Test001ChartView(TemplateView):
csrf_protected_method = method_decorator(csrf_protect)
I test it and works well.