반응형
flask

Simple Python Web API Server

쉽고 빠르게 웹 API 서버를 만드는 방법.
언어는 Python
아래 방식을 참고하면 아주 빠르고 간단하고 쉽게 API 서버를 만들 수 있다. 여기에 서비스에 필요한 작업들을 추가만 해 주면 된다.
POST 방식으로 JSON 포맷을 사용하여 통신하는 것을 추천한다.

개발툴로 PyCharm을 사용
패키지 설치

# pip install flask
# pip install flask_restful

아래 코드를 작성한다.

  • testsvr . py
'''
test api server
'''

from flask import Flask, request
from flask_restful import Resource, Api
from flask.views import MethodView

import logging
import json,base64

import os, sys
import datetime
import threading, time

app = Flask(__name__)
api = Api(app)

log = logging.basicConfig(filename='testsvr.log', level=logging.INFO)

# 로깅을 전부 끄기
# logging.getLogger('werkzeug')
# log = logging.get
# log.disabled = True
# app.logger.disabled = True

'''
/apitest1
'''
class apitest1(MethodView):
    def get(self):
        data = request.args
        print('recv:', data)  # dictionary
        abc = data.get('abc')
        if abc :
            result = 'This is GET method!'+str(abc)
        else:
            result = 'Hello World! input abc'
        return result

    def post(self):
        # get과 동일하게 작동
        return self.get()


'''
/sum
'''
class sum(MethodView):
    def get(self):
        data = request.args
        print('recv:', data)  # dictionary
        return 'Hello.'

    def post(self):
        '''
        JSON으로 받아서 작업 후 JSON으로 결과 반환
        '''
        logging.info('sum test')
        # print('request.data=', request.data)  # binary data read all
        data=request.get_json(force=True) # parse json string
        print('request.json=', data)
        a = data['a']
        b = data['b']
        now = datetime.datetime.now()
        print(now)
        timestr = now.strftime('%Y%m%d %H:%M:%S')
        result = {
            'sum':int(a+b),
            'time':timestr
        }
        logging.info('result='+json.dumps(result))
        return result


api.add_resource(apitest1, '/apitest1')
api.add_resource(sum, '/sum')

port = 18899

if __name__=='__main__':
    print('Start Server... port=', port)
    logging.info('start server')
    app.run(host='0.0.0.0', port=port, debug=True)
    # 디버그 모드로 하면 소스 수정시 자동으로 서버 재시작이 된다.


서버 구동 스크립트는 다음을 참고

---testsvr.bat---
c:\python37\scripts\python testsvr.py

---testsvr.sh---
#!/bin/bash  
  
# [python env path...]/bin/python testsvr.py  
# linux ex)  
/opt/anaconda3/envs/tensorflow/bin/python testsvr.py  
# windows command ex)  
# c:\python37\scripts\python testsvr.py

테스트 화면 : GET 방식
주소: http://localhost:18899/apitest1?abc=123&def=456
image

테스트 화면 : POST 방식, 덧셈 API
주소: http://localhost:18899/sum
POST 데이터: {“a”:5, “b”:6}
image

Written with StackEdit.

반응형
screenvideocapture

Screen Capture (Video)

PC 화면의 일부를 캡쳐하는 방법은 많이 있는데…
PC 화면의 일부나 특정 윈도우를 간단하게 영상을 캡쳐하고 싶을 때는 어떻게 해야 할까? 무료 유틸리티를 사용하고 싶다.

먼저 Free License 유틸리티로 동영상 처리 관련된 강력한 프로그램인 ffmpeg를 권장한다.
물론 사용 방법은 커맨드 등을 익혀야 되서 복잡할 수 있지만, 여기서는 이것을 dos batch script로 만들어서 한 번만 만들어 두면 이후에 공짜로 편하게 사용할 수 있다.

  1. 프로그램 설치

구글에서 ffmpeg windows download 라고 검색해서 설치한다.
잘 모르겠으면 윈도우 패키지 링크 주소는
ffmpeg windows 64 bit binary download
다운 받은 파일을 열어 압축을 풀면 bin 폴더가 있다. bin 폴더의 파일들을 c:\windows에 복사하자. (별도 유틸리티 폴더를 만들고, 환경설정으로 PATH에 설정해 두는 것이 좋긴하지만 귀찮으면 위와 같이 한다.)
이제 DOS 커맨드 창에서 ffmpeg라고 실행해서 잘 되는지 확인한다.
image

  1. 스크립트 작성

스크립트1: 특정 윈도우 창만 캡쳐하기
ffmpeg_videocap.bat “윈도우제목” "파일명"
파일명.mp4로 파일이 생성됨.

@echo off
if "%1"=="" goto usage

:: by crazyj7@gmail.com
:: famerate ; 24, 30. 60 
:: 파일 확장자는 mp4, avi, mpg 등 
:: drawmouse : 마우스 커서를 보여줄지 여부 (1/0)

ffmpeg -y -rtbufsize 100M -f gdigrab -framerate 30 -probesize 10M -draw_mouse 0 -i title="%1" -c:v libx264 -r 30  -preset ultrafast -tune zerolatency -crf 25 -pix_fmt yuv420p -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" "%2.mp4"

goto:eof

:usage
echo Usage)
echo %0 "window title" "filename"
goto:eof

스크립트2: 전체 화면 동영상 캡쳐하기 (모니터가 2개면 둘 다 캡쳐된다.)
ffmpeg_videocap_fullscreen.bat "파일명"

파일명.mp4 파일 생성됨.

@echo off
if "%1"=="" goto usage
 
:: crazyj7@gmail.com 
:: famerate ; 24, 30. 60 
:: 파일 확장자는 mp4, avi, mpg 등 
:: drawmouse : 마우스 커서를 보여줄지 여부 (1/0)
 
ffmpeg -y -rtbufsize 100M -f gdigrab -framerate 30 -probesize 10M -draw_mouse 1 -i desktop -c:v libx264 -r 30 -preset ultrafast -tune zerolatency -crf 25 -pix_fmt yuv420p "%1.mp4"
 
goto:eof
  
:usage
echo Usage)
echo %0 "filename"
goto:eof

스크립트3: 전체 화면 동영상 캡쳐하기. (모니터2개인경우 모니터1만)
주의! 모니터1의 해상도 값으로 코드를 바꿔줘야 한다. (1280x1080 예이다.)
특정 영역 캡쳐하기도 된다. (offset과 크기 조정)
ffmpeg_videocap_full1280x1080.bat “파일명”

@echo off
if "%1"=="" goto usage

:: crazyj7@gmail.com
:: famerate ; 24, 30. 60 
:: 파일 확장자는 mp4, avi, mpg 등 
:: drawmouse : 마우스 커서를 보여줄지 여부 (1/0)

ffmpeg -y -rtbufsize 100M -f gdigrab -framerate 30 -probesize 10M -draw_mouse 1 -offset_x 0 -offset_y 0 -video_size 1920x1080 -i desktop -c:v libx264 -r 30 -preset ultrafast -tune zerolatency -crf 25 -pix_fmt yuv420p "%1.mp4"

goto:eof

:usage
echo Usage)
echo %0 "filename"
goto:eof

  1. 실행
  • 커맨드 실행 종료 (녹화 종료)는 q 또는 ^c(컨트롤c)

특정 윈도우만 동영상 캡쳐를 하려면 아래와 같이 한다.
윈도우 타이틀은 창의 상단에 타이틀바에 기록된 스트링이다. (없거나 못 찾을 경우는 화면 일부영역 캡쳐를 참고하기 바란다.)

c:\temp> ffmpeg_videocap “stackedit” “aaa”
"stackedit"란 제목의 창을 찾아 aaa.mp4 동영상 파일을 생성한다.
aaa

전체화면 동영상 캡쳐
c:\temp> ffmpeg_videofullscreen “full”
전체 화면을 녹화하여 full.mp4 파일이 생성된다. (모니터가 2개면 둘 다 나온다.)
full

모니터1만 캡쳐 또는 일부 영역만 캡쳐
(일부 영역을 지정하려면 스크립트를 수정하여 offset과 size를 조정하면 된다.)
c:\temp> ffmpeg_videofullscreen_1920_1080 “full2”
모니터1만 (1920x1080 해상도) 녹화하여 full2.mp4 동영상 파일을 생성한다.
full2

  1. 보너스 (동영상을 gif로)

생성한 동영상 파일을 움직이는 gif 파일로 변환하기
ffmpeg -i aaa.mp4 aaa.gif
브라우저에 aaa.gif 파일을 드래그드롭하면 움직이는 gif 파일이 재생된다. (웹에 올리기 편하다.)

image

Written with StackEdit.

'Develop > Windows' 카테고리의 다른 글

DOS Batch Script  (0) 2019.10.06
curl 사용법/HTTP 테스트  (0) 2019.10.01
windows 10 kernel structure  (0) 2015.08.28
윈도우8/8.1에서 visual studio 2008 설치실패시 / .net framework 설치  (0) 2015.08.20
64비트 프로그래밍  (2) 2015.06.05
반응형
graphsetting_reset

그래프 설정 리셋

가끔가다 그래프 설정의 변경으로 잘 나오던 그래프가 깨지는 경우가 종종 나온다. matplotlib과 seaborn 등 여러가지를 막 섞어 쓰다보면 가끔 발생한다.

다음과 같이 잘 나오던 그래프가
image

어느 순간 다시 똑같은 코드를 실행했는데, 이런 결과가…
(위와 아래는 똑같은 코드다.)
image

Jupyter Lab에서 커널을 다시 기동해야지만 다시 원래대로 나오는데, 마찬가지로 중간에 어떤 작업으로 인해 그래프 설정이 변경되면 위와 같이 다시 이상하게 출력되었다. 나중에 원인을 찾아보니… 아래의 sns.set() 코드였다.
image
이후 부터는 이상한 그래프가 출력된 것이다. 원상 복구를 하는 것을 찾아보다가 reset해 주는 코드를 찾았다.
또한 설정값 변경된 것을 확인해 주는 코드도 있다.

image
위와 같이 pltconfig_default() 함수를 만들어 사용하면 원래 설정대로 복원된다.

참고로 다음은 plot 설정값이 디폴트에서 변경된 내역을 찾아주는 코드다.

# plot 환경설정 기본값과 달라진 점
class DictDiffer(object):
    """
    Calculate the difference between two dictionaries as:
    (1) items added
    (2) items removed
    (3) keys same in both but changed values
    (4) keys same in both and unchanged values
    """
    def __init__(self, current_dict, past_dict):
        self.current_dict, self.past_dict = current_dict, past_dict
        self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
        self.intersect = self.set_current.intersection(self.set_past)
    def added(self):
        return self.set_current - self.intersect 
    def removed(self):
        return self.set_past - self.intersect 
    def changed(self):
        return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
    def unchanged(self):
        return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])
    
def pltconfig_check():
    d=DictDiffer(plt.rcParams, plt.rcParamsDefault)
    for it in d.changed():
        print(it, plt.rcParamsDefault[it], plt.rcParams[it])

위에서 sns 환경설정 변경으로 기존의 세팅과 변경된 내역을 확인해 보자.
image
상당히 많은 설정값들이 변경된 것을 확인하였다.

image

다시 원래 디폴트로 돌아온 것이다. 위에서 나온 변경내역은 matplotlib inline으로 인해 변경된 내역이므로 신경쓰지 않아도 된다.

Author: crazyj7@gmail.com
Written with StackEdit.

'Python' 카테고리의 다른 글

초간단 python 서버만들기2  (0) 2019.09.25
초간단 웹API서버만들기  (0) 2019.09.25
JupyterLab에서 Python Script(.py)실행하기  (0) 2019.09.19
Jupyter Notebook 멀티라인출력  (0) 2019.09.19
진행(progress)바/ tqdm  (2) 2019.08.28

+ Recent posts