Commit 1a79545f authored by Wichit Sombat's avatar Wichit Sombat

bosscommit

parent 3ec43ad7
*.pyc
dist/
build/
*.egg-info/
.tox/
.coverage
# getposter
Search and show poster from imdb
# Installation
$ pip install --user requests Pillow bs4
$ pip install -U --user .
# Usage
$ getposter -s "The Matrix"
$ getposter "Jumanji"
import sys
import click
import requests
import json
import re
from PIL import Image
try:
from StringIO import StringIO
except: # when using python3.x
from io import BytesIO, StringIO
from bs4 import BeautifulSoup
#IMDBSEARCHURL = 'http://www.imdb.com/search/title?title=The%20Godfather&page=1&ref_=adv_nxt'
IMDBSEARCHURL = 'http://www.imdb.com/search/title?title={}&page={}&ref_=adv_nxt'
def extractmovieinfo(div):
data = {}
# id & title & runtime
img = div.find_next('img')
data['id'] = img['data-tconst']
data['title'] = img['alt']
try:
data['runtime'] = div.find_next('span', attrs={'class':'runtime'}).text
except: pass
# url & year
h3 = div.find_next('h3')
data['url'] = 'http://www.imdb.com{}'.format(h3.find_next('a')['href'])
year = h3.find_next('span', attrs={'class': ['lister-item-year',
'text-muted unbold']}).text
data['year'] = re.findall(r'\d+', year)[0]
# gross
try:
p = div.find_all('span')
data['gross'] = int(p[-1]['data-value'].replace(',',''))
except: pass
# rating
try:
rate = div.find_next('div', attrs={'class':['rating']}).find_all('meta')
data['rate'] = float(rate[0]['content'])
data['total'] = int(rate[1]['content'])
data['vote'] = int(rate[2]['content'])
except: pass
return data
def searchmovies(title):
b = BeautifulSoup(requests.get(IMDBSEARCHURL.format(title, 1)).text, 'lxml')
return b.find_all('div', attrs={'class': ['lister-item', 'mode-advanced']})
@click.command()
@click.option('--search', '-s', is_flag=True, help='search all result from text.')
@click.argument('title', required=False)
def main(title, search):
"""Search and show movie poster from search."""
if title:
movies = [ extractmovieinfo(div) for div in searchmovies(title) ]
if search:
click.echo('seaching for title = {}'.format(title))
print('{:10} {:30} {:^6} {:^5} {:>15}'.format(
'id', 'title', 'year', 'rate', 'gross'))
for m in movies:
try:
print('{:10} {:30} {:6} {:6} {:15}'.format(
m['id'], m['title'][:30], m['year'], m['rate'], m['gross']))
except: pass
else:
movie = movies[0]
click.echo('showing poster "{}"'.format(movie['title']))
try:
print('{:10} {:30} {:^6} {:^5} {:>15}'.format(
'id', 'title', 'year', 'rate', 'gross'))
print('{:10} {:30} {:6} {:6} {:15}'.format(
movie['id'], movie['title'][:30], movie['year'], movie['rate'], movie['gross']))
except: pass
b = BeautifulSoup(requests.get(movie['url']).text, 'lxml')
poster = b.find_all('div', attrs={'class':'poster'})[0]
imgurl = poster.find_next('img')['src']
req = requests.get(imgurl)
if sys.version_info >= (3,0):
img = Image.open(BytesIO(req.content))
img.show()
else:
img = Image.open(StringIO(req.content))
img.show()
else:
click.echo('usage: getposter "The Movie Title"')
[wheel]
universal = 1
"""
Search and show imdb movie poster.
"""
from setuptools import find_packages, setup
dependencies = ['click']
setup(
name='getposter',
version='0.2.0',
url='https://github.com/wichit2s/getposter',
license='BSD',
author='Wichit Sombat',
author_email='wichit.s@ubu.ac.th',
description='My Tool does one thing, and one thing well.',
long_description=__doc__,
packages=find_packages(exclude=['tests']),
include_package_data=True,
zip_safe=False,
platforms='any',
install_requires=dependencies,
entry_points={
'console_scripts': [
'getposter = getposter.cli:main',
],
},
classifiers=[
# As from http://pypi.python.org/pypi?%3Aaction=list_classifiers
# 'Development Status :: 1 - Planning',
# 'Development Status :: 2 - Pre-Alpha',
# 'Development Status :: 3 - Alpha',
'Development Status :: 4 - Beta',
# 'Development Status :: 5 - Production/Stable',
# 'Development Status :: 6 - Mature',
# 'Development Status :: 7 - Inactive',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Operating System :: MacOS',
'Operating System :: Unix',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
import pytest
from click.testing import CliRunner
from getposter import cli
@pytest.fixture
def runner():
return CliRunner()
def test_cli(runner):
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert not result.exception
assert result.output.strip() == 'Hello, world.'
def test_cli_with_option(runner):
result = runner.invoke(cli.main, ['--as-cowboy'])
assert not result.exception
assert result.exit_code == 0
assert result.output.strip() == 'Howdy, world.'
def test_cli_with_arg(runner):
result = runner.invoke(cli.main, ['Wichit'])
assert result.exit_code == 0
assert not result.exception
assert result.output.strip() == 'Hello, Wichit.'
[tox]
envlist=py26, py27, py33, py34, pypy, flake8
[testenv]
commands=py.test --cov getposter {posargs}
deps=
pytest
pytest-cov
[testenv:flake8]
basepython = python2.7
deps =
flake8
commands =
flake8 getposter tests --max-line-length=120
{
"tests/test_cli.py": true
}
\ No newline at end of file
.env
*.pyc
dist/
build/
*.egg-info/
.tox/
.coverage
# linux-lab
>ผู้พัฒนาโครงการ : Piyawat Junto
>รหัสนักศึกษา: 59110440260
## จุดประสงค์
>ฝึกใช้ Phython ทำ CLI โปรแกรม ตามแบบ githubavatar
## สิ่งที่ต้องพัฒนาตัวเองให้ดีขึ้น
1. จะตั้งใจเรียน
2. ไม่เอามือถือขึ้นมาเล่นอีกแล้ว
3. จะตั้งใจอ่านสอบปลายภาคทุกวิชา
4. จะใช้เงินอย่างประหยัด
5. ทบทวนการเรียนทุกครั้งหลังเลิกคาบ
6. เล่นเกมส์ให้น้อยลง
import click
import requests
import sys
from PIL import Image
try:
from StringIO import StringIO
except: # when using python3.x
from io import BytesIO, StringIO
@click.command()
@click.option('--as-author', '-c', is_flag=True, help='Computer Science at UBU')
@click.argument('name', default='wichit2s', required=False)
def main(name, as_author):
"""Get Github Avatar"""
#greet = 'Howdy' if as_cowboy else 'Hello'
#click.echo('{0}, {1}.'.format(greet, name))
api_user_url = 'https://api.github.com/users/{}'.format(name)
json = requests.get(api_user_url).json()
req = requests.get(json['avatar_url'])
if sys.version_info >= (3,0):
img = Image.open(BytesIO(req.content))
img.show()
else:
img = Image.open(StringIO(req.content))
img.show()
"""
Get Github Avatar
"""
from setuptools import find_packages, setup
dependencies = ['Click', 'Pillow', 'requests']
setup(
name='githubavatar',
version='0.2.0',
url='https://github.com/wichit2s/githubavatar',
license='BSD',
author='CS UBU',
author_email='wichit.s@ubu.ac.th',
description='Get Github Avatar',
long_description=__doc__,
packages=find_packages(exclude=['tests']),
include_package_data=True,
zip_safe=False,
platforms='any',
install_requires=dependencies,
entry_points={
'console_scripts': [
'githubavatar = githubavatar.cli:main',
],
},
classifiers=[
# As from http://pypi.python.org/pypi?%3Aaction=list_classifiers
# 'Development Status :: 1 - Planning',
# 'Development Status :: 2 - Pre-Alpha',
# 'Development Status :: 3 - Alpha',
'Development Status :: 4 - Beta',
# 'Development Status :: 5 - Production/Stable',
# 'Development Status :: 6 - Mature',
# 'Development Status :: 7 - Inactive',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Operating System :: MacOS',
'Operating System :: Unix',
'Operating System :: Microsoft :: Windows',
#'Programming Language :: Python',
#'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
import pytest
from click.testing import CliRunner
from githubavatar import cli
@pytest.fixture
def runner():
return CliRunner()
def test_cli(runner):
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert not result.exception
assert result.output.strip() == 'Hello, world.'
def test_cli_with_option(runner):
result = runner.invoke(cli.main, ['--as-cowboy'])
assert not result.exception
assert result.exit_code == 0
assert result.output.strip() == 'Howdy, world.'
def test_cli_with_arg(runner):
result = runner.invoke(cli.main, ['CS'])
assert result.exit_code == 0
assert not result.exception
assert result.output.strip() == 'Hello, CS.'
[tox]
envlist=py26, py27, py33, py34, pypy, flake8
[testenv]
commands=py.test --cov githubavatar {posargs}
deps=
pytest
pytest-cov
[testenv:flake8]
basepython = python2.7
deps =
flake8
commands =
flake8 githubavatar tests --max-line-length=120
# วิธีการเขียน CLI ด้วย Python
## 1. ติดตั้ง
```sh
pip install --user cookiecutter
pip install --user virtualenv
```
## 2. สร้างโปรแกรมใหม่จาก template บน github
```sh
cookiecutter https://github.com/nvie/cookiecutter-python-cli.git
```
... จากนั้น กรอกข้อมูลเกี่ยวกับโปรแกรมใหม่ จนครบ
```sh
Cloning into 'cookiecutter-python-cli'...
remote: Counting objects: 64, done.
remote: Total 64 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (64/64), done.
Checking connectivity... done.
full_name (default is "Vincent Driessen")? Name LastName
email (default is "vincent@3rdcloud.com")? xxx.yy.59@ubu.ac.th
github_username (default is "nvie")? xxxyy
project_name (default is "My Tool")? Get Github Avatar
repo_name (default is "python-mytool")? githubavatar
pypi_name (default is "mytool")? githubavatar
script_name (default is "my-tool")? githubavatar
package_name (default is "my_tool")? githubavatar
project_short_description (default is "My Tool does one thing, and one thing well.")? Get Github Avatar
release_date (default is "2014-09-04")? 2017-11-02
year (default is "2014")? 2017
version (default is "0.1.0")?
```
## 3. เริ่มเขียนโปรแกรม
(remove virtualenv)
```sh
cd githubavatar
```
- ติดตั้ง package ที่จำเป็น
```sh
pip install --user click requests Pillow
```
- เปิดไฟล์ เพื่อทำการแก้ไขคำสั่ง
```sh
gedit githubavatar/githubavatar/cli.py &
```
- แก้ไขคำสั่งเป็น
```python
import click
import requests
from PIL import Image
from StringIO import StringIO
@click.command()
@click.option('--as-author', '-c', is_flag=True, help='Computer Science at UBU')
@click.argument('name', default='wichit2s', required=False)
def main(name, as_author):
"""Get Github Avatar"""
#greet = 'Howdy' if as_cowboy else 'Hello'
#click.echo('{0}, {1}.'.format(greet, name))
api_user_url = 'https://api.github.com/users/{}'.format(name)
json = requests.get(api_user_url).json()
req = requests.get(json['avatar_url'])
img = Image.open(StringIO(req.content))
img.show()
```
- บันทึกแล้วปิด
- ติดตั้ง
```sh
pip install --user .
```
- ทดสอบ
```sh
githubavatar wichit2s
githubavatar joinshena
```
# Links
## IMDB API
* http://www.omdbapi.com/ $\to$ https://pypi.python.org/pypi/omdb
* https://imdbpy.sourceforge.io/
* https://github.com/msaqib4203/IMDB-API
* https://www.themoviedb.org/
import os
gettext = lambda s: s
DATA_DIR = os.path.dirname(os.path.dirname(__file__))
"""
Django settings for csubusite project.
Generated by 'django-admin startproject' using Django 1.8.18.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 't4ru*!asf@jf1)l$dclfkw%*ea168q060gkw=0xm#1q(wc_x7d'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
ROOT_URLCONF = 'csubusite.urls'
WSGI_APPLICATION = 'csubusite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en'
TIME_ZONE = 'Asia/Bangkok'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
STATIC_ROOT = os.path.join(DATA_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'csubusite', 'static'),
)
SITE_ID = 1
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'csubusite', 'templates'),],
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.i18n',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.template.context_processors.csrf',
'django.template.context_processors.tz',
'sekizai.context_processors.sekizai',
'django.template.context_processors.static',
'cms.context_processors.cms_settings'
],
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.Loader'
],
},
},
]
MIDDLEWARE_CLASSES = (
'cms.middleware.utils.ApphookReloadMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.language.LanguageCookieMiddleware'
)
INSTALLED_APPS = (
'djangocms_admin_style',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.staticfiles',
'django.contrib.messages',
'cms',
'menus',
'sekizai',
'treebeard',
'djangocms_text_ckeditor',
'filer',
'easy_thumbnails',
'djangocms_column',
'djangocms_link',
'cmsplugin_filer_file',
'cmsplugin_filer_folder',
'cmsplugin_filer_image',
'cmsplugin_filer_utils',
'djangocms_style',
'djangocms_snippet',
'djangocms_googlemap',
'djangocms_video',
'autotranslate',
'csubusite'
)
LANGUAGES = (
## Customize this
('en', gettext('en')),
)
CMS_LANGUAGES = {
## Customize this
'default': {
'public': True,
'hide_untranslated': False,
'redirect_on_fallback': True,
},
1: [
{
'public': True,
'code': 'en',
'hide_untranslated': False,
'name': gettext('en'),
'redirect_on_fallback': True,
},
],
}
CMS_TEMPLATES = (
## Customize this
('fullwidth.html', 'Fullwidth'),
('sidebar_left.html', 'Sidebar Left'),
('sidebar_right.html', 'Sidebar Right')
)
CMS_PERMISSION = True
CMS_PLACEHOLDER_CONF = {}
DATABASES = {
'default': {
'CONN_MAX_AGE': 0,
'ENGINE': 'django.db.backends.sqlite3',
'HOST': 'localhost',
'NAME': 'project.db',
'PASSWORD': '',
'PORT': '',
'USER': ''
}
}
MIGRATION_MODULES = {
}
THUMBNAIL_PROCESSORS = (
'easy_thumbnails.processors.colorspace',
'easy_thumbnails.processors.autocrop',
'filer.thumbnail_processors.scale_and_crop_with_subject_location',
'easy_thumbnails.processors.filters'
)
{% load cms_tags menu_tags sekizai_tags %}
<!doctype html>
<html>
<head>
<title>{% block title %}This is my new project home page{% endblock title %}</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style type="text/css">
.nav {
padding-left: 0;
}
.nav li {
display: inline;
list-style-type: none;
padding-right: 20px;
}
.container {
width: 940px;
margin: 0 auto
}
.content {
float: left;
width: 80%;
}
.sidebar {
float: left;
width: 20%;
}
</style>
{% render_block "css" %}
</head>
<body>
{% cms_toolbar %}
<div class="container">
<ul class="nav">
{% show_menu 0 100 100 100 %}
</ul>
{% block content %}{% endblock content %}
</div>
{% render_block "js" %}
</body>
</html>
{% extends "base.html" %}
{% load cms_tags %}
{% block title %}{% page_attribute "page_title" %}{% endblock title %}
{% block content %}
{% placeholder "content" %}
{% endblock content %}
{% extends "base.html" %}
{% load cms_tags %}
{% block title %}{% page_attribute "page_title" %}{% endblock title %}
{% block content %}
<div class="sidebar">
{% placeholder "sidebar" %}
</div>
<div class="content">
{% placeholder "content" %}
</div>
{% endblock content %}
{% extends "base.html" %}
{% load cms_tags %}
{% block title %}{% page_attribute "page_title" %}{% endblock title %}
{% block content %}
<div class="content">
{% placeholder "content" %}
</div>
<div class="sidebar">
{% placeholder "sidebar" %}
</div>
{% endblock content %}
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from cms.sitemaps import CMSSitemap
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.static import serve
admin.autodiscover()
urlpatterns = [
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': {'cmspages': CMSSitemap}}),
]
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^', include('cms.urls')),
)
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
] + staticfiles_urlpatterns() + urlpatterns
"""
WSGI config for csubusite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "csubusite.settings")
application = get_wsgi_application()
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "csubusite.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
django-cms<3.5
djangocms-admin-style>=1.2,<1.3
django-treebeard>=4.0,<5.0
djangocms-text-ckeditor>=3.2.1
djangocms-link>=1.8
djangocms-style>=1.7
djangocms-googlemap>=0.5
djangocms-snippet>=1.9
djangocms-video>=2.0
djangocms-column>=1.6
easy_thumbnails
django-filer>=1.2
cmsplugin-filer>=1.1
Django<1.9
pytz
django-classy-tags>=0.7
html5lib>=0.999999,<0.99999999
Pillow>=3.0
django-sekizai>=0.9
six
\ No newline at end of file
# การพัฒนาเว็บโดยใช้ python บน Linux
มาฝึกใช้ django-cms ในการสร้างเว็บไซต์ชื่อ csubusite
ความรู้ที่ควรมี python, CMS, html
อ้างอิง: http://docs.django-cms.org/en/release-3.4.x/introduction/index.html
## 1. ติดตั้ง
```sh
virtualenv .env
source .env/bin/activate
pip install --upgrade pip
pip install djangocms-installer
```
## 2. สร้าง directory และ csubusite
```sh
mkdir csubuproject
cd csubuproject
djangocms -f -p . csubusite
```
## 3. เปิด server ให้บริการ
```sh
python manage.py runserver
```
## 4. เข้าเว็บไซต์เพื่อสร้าง page
http://localhost:8000/admin
โดยใช้ user/password เป็น admin/admin
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment