2021 04 Flask
Flask Code Flask Json 처리방법

{flask 에서 json 데이터를 받아서 처리할 때 reqeust.get_json() 혹은 request.json 을 이용할 수 있는데, mime type을 application/json 타입으로 보내는데, {} 없이 빈 JSON 문자열 조차도 안 보내는 경우가 있을수가 있다.from flask import Flask  from flask import request  app = Flask(__name__)@app.route("/test", methods=['POST'])def test():      print request.json #request.get_json()    return "Hello World!"이런 경우 flask 에서는 400 bad request 를 응답값으로 보낸다. 보내는 이유는 parsing fail이 발생하고 on_json_loading_failed(e) 함수가 실행되게 된다. 이 함수는 JSON Decode 실패 시 400 Bad Request를 보내느 것이 기본 구현으로 되어 있다. JSON parsing fail 이 나더라도 400 Bad Request 외의 다른 행동을 정의하기 위해서는 아래와 같은 방법을 사용하면 된다.1. on_json_loading_failed() 재정의 하기앞서 on_json_loading_failed 함수로 인해서 400 Bad Request 가 리턴되기 때문에 해당 함수를 다르게 동작하도록 재정의 하고, 재정의한 함수를 request.on_json_loading_failed 에 연결 시킬 수가 있다. 이 방법이 좋은 점은 함수를 재정의 함으로써 복잡한 기능을 JSON parsing fail 이 발생 했을때 대응 할수가 있다. 예를 들면, 400 bad request 와 함께 JSON 응답을 보내게 할 수도 있고, 특정한 로그를 남기거나 하는 등의 행동을 정의 할 수가 있다.아래의 예제에서는 에러가 발생했을 때, 기본 빈 dict을 반환하도록 구성하였다. 이렇게 하면 마음놓고 get_json()을 사용 할 수가 있다.def on_json_loading_failed_return_dict(e):      return {}@app.route("/test", methods=['POST'])def test():      request.on_json_loading_failed = on_json_loading_failed_return_dict    print request.get_json()    return "Hello World!" 2. get_json() silent 파라미터 활용get_json() 함수는 몇가지 파라미터를 제공하는데 그 중에서 silent 파라미터는 JSON parsing fail 에 대해서 None 처리 여부를 설정할 수 있다. 기본값을 False인데, 명시적으로 True 로 주면 get_json() 호출시 에러가 나지 않고 None을 리턴한다.print request.get_json(silent=True)  Parameters:force – if set to True the mimetype is ignored.silent – if set to True this method will fail silently and return None.cache – if set to True the parsed JSON data is remembered on the request.어떤 방식을 선호하는지는 개인이나 프로젝트 성격에 따라 다를것 같다. 모든 API가 JSON 으로 데이터를 전달하는 방식이라면, on_json_loading_failed() 함수를 재정의하고 decorator 등을 활용하는게 좋을것 같다. (필자 역시 최근의 프로젝트에서 그렇게 활용했다.)참고로 flask 0.11 버전에서는 is_json 이 추가되었는데 이것은 parsing fail 을 감지하는 것이 아니라, mimetype 이 application/json 인지 아닌지를 True | False 로 반환하는 역할을 한다.

작성일 :2021-04-28 06:05 / 조회수: 215회
2021 04 Flask
Flask Code flask request 데이터

The docs describe the attributes available on the request. In most common cases request.data will be empty because it's used as a fallback: request.data Contains the incoming request data as string in case it came with a mimetype Flask does not handle. request.args: the key/value pairs in the URL query string request.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded request.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded. request.values: combined args and form, preferring args if keys overlap request.json: parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type. All of these are MultiDict instances (except for json). You can access values using: request.form['name']: use indexing if you know the key exists request.form.get('name'): use get if the key might not exist request.form.getlist('name'): use getlist if the key is sent multiple times and you want a list of values. get only returns the first value.

작성일 :2021-04-24 08:34 / 조회수: 114회
2021 04 flask
Flask Code Flask apache WSGIPassAuthorization

이미지 삽입 Raspberry Pi List 시리즈    #1. Monitoring 개요, wflask.conf에 VirtualHost 설정으로 추가WSGIPassAuthorization on

작성일 :2021-04-11 14:39 / 조회수: 201회
2021 04 Flask
Flask Code Flask + apache2 + mod_wsgi

이미지 삽입 Raspberry Pi List 시리즈    #1. Default 개요, Apache2 + Flask + mod_wsgi 연결 끝- not ssl / not multi wsgi아파치 서버 설정 : /etc/apache2/apache2.conf 아파치 VirtualHost 설정 : /etc/apache2/site-available/default.conf 아파치 웹서버 가상 호스트 기본 설정 : /etc/apache2/site-available/000-default.conf #우분투 패키지 업데이트 $sudo apt-get update #아파치2 설치 $sudo apt-get install apache2 #wsgi 설치 (web server gateway interface server 설치 = middleware) $sudo apt-get install libapache2-mod-wsgi-py3 $sudo a2enmod wsgi -- 안해도 됨 위에 명령어에서 자동으로 처리 #pip 배포 패키지 설치 $sudo apt-get install python3-pip #pip 최신 버전으로 업그레이드 $sudo pip3 install --upgrade pip #flask 웹 프레임워크 설치 $sudo pip3 install flask $cd ~/ $sudo mkdir flask $sudo ln -sT ~/flask /var/www/flask #링크 파일 생성(심볼릭 링크: 윈도우 바로가기와 유사) ln 옵션 원본파일 대상파일 $cd flask$sudo vi flaskapp.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' $sudo vi app.wsgi import sys sys.path.insert(0, '/var/www/flask') from flaskapp import app as application$sudo vi /etc/apache2/sites-available/flask.conf <VirtualHost *:80> ServerName localhost WSGIDaemonProcess app threads=5 WSGIScriptAlias / /var/www/flask/app.wsgi DocumentRoot /var/www/flask <Directory /var/www/flask> WSGIProcessGroup app WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>$cd /etc/apache2/sites-available $sudo a2dissite 000-default $sudo a2ensite flask.conf $sudo service apache2 restart$vi /etc/apache2/apache2.conf <document /> 삭제#2. multiple apps개요,서버이름, wsgi, 프로세스 이름 변경$sudo vi /etc/apache2/sites-available/flask.conf <VirtualHost *:80> ServerName calcs.kr WSGIDaemonProcess app threads=5 WSGIScriptAlias / /var/www/flask/app.wsgi DocumentRoot /var/www/flask <Directory /var/www/flask> WSGIProcessGroup app WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> <VirtualHost *:80> ServerName percent.calcs.kr WSGIDaemonProcess percent threads=5 WSGIScriptAlias / /var/www/flask/app.wsgi DocumentRoot /var/www/flask <Directory /var/www/flask> WSGIProcessGroup percent WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> #3. ssl개요,SSL 인증서 발급$apt install letsencrypt$service apache2 stop$sudo letsencrypt certonly -w /var/www -d calcs.kr -d percent.calcs.kr1번(standalone)AN/etc/letsencrypt/live/[domain]/파일들은 총 4가지가 존재한다.cert.pem : 인증서 파일chain.pem : 인증서 발급자 파일fullchain.pem : cert.pem+chain.pemprivkey.pem : 인증암호를 복호화하는 개인키cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/back-ssl.conf$vi /etc/apache2/sites-available/back-ssl.conf SSLEngine on SSLProtocol all -SSLv2 -SSLv3 SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA SSLHonorCipherOrder on SSLCertificateFile “/etc/letsencrypt/live/[폴더명]/cert.pem” SSLCertificateKeyFile “/etc/letsencrypt/live/[폴더명]/privkey.pem” SSLCertificateChainFile “/etc/letsencrypt/live/[폴더명]/chain.pem” SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire 주석 해제<IfModule mod_ssl.c> <VirtualHost _default_:443> ServerAdmin reasley.com@gamil.com DocumentRoot /var/www/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with "a2disconf". #Include conf-available/serve-cgi-bin.conf # SSL Engine Switch: # Enable/Disable SSL for this virtual host. SSLEngine on SSLProtocol all -SSLv2 -SSLv3 SSLHonorCipherOrder on SSLCertificateFile "/etc/letsencrypt/live/reasley.com-0001/cert.pem" SSLCertificateKeyFile "/etc/letsencrypt/live/reasley.com-0001/privkey.pem" SSLCertificateChainFile "/etc/letsencrypt/live/reasley.com-0001/chain.pem" # A self-signed (snakeoil) certificate can be created by installing # the ssl-cert package. See # /usr/share/doc/apache2/README.Debian.gz for more info. # If both key and certificate are stored in the same file, only the # SSLCertificateFile directive is needed. #SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem #SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key # Server Certificate Chain: # Point SSLCertificateChainFile at a file containing the # concatenation of PEM encoded CA certificates which form the # certificate chain for the server certificate. Alternatively # the referenced file can be the same as SSLCertificateFile # when the CA certificates are directly appended to the server # certificate for convinience. #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt # Certificate Authority (CA): # Set the CA certificate verification path where to find CA # certificates for client authentication or alternatively one # huge file containing all of them (file must be PEM encoded) # Note: Inside SSLCACertificatePath you need hash symlinks # to point to the certificate files. Use the provided # Makefile to update the hash symlinks after changes. #SSLCACertificatePath /etc/ssl/certs/ #SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt # Certificate Revocation Lists (CRL): # Set the CA revocation path where to find CA CRLs for client # authentication or alternatively one huge file containing all # of them (file must be PEM encoded) # Note: Inside SSLCARevocationPath you need hash symlinks # to point to the certificate files. Use the provided # Makefile to update the hash symlinks after changes. #SSLCARevocationPath /etc/apache2/ssl.crl/ #SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl # Client Authentication (Type): # Client certificate verification type and depth. Types are # none, optional, require and optional_no_ca. Depth is a # number which specifies how deeply to verify the certificate # issuer chain before deciding the certificate is not valid. #SSLVerifyClient require #SSLVerifyDepth 10 # SSL Engine Options: # Set various options for the SSL engine. # o FakeBasicAuth: # Translate the client X.509 into a Basic Authorisation. This means that # the standard Auth/DBMAuth methods can be used for access control. The # user name is the `one line' version of the client's X.509 certificate. # Note that no password is obtained from the user. Every entry in the user # file needs this password: `xxj31ZMTZzkVA'. # o ExportCertData: # This exports two additional environment variables: SSL_CLIENT_CERT and # SSL_SERVER_CERT. These contain the PEM-encoded certificates of the # server (always existing) and the client (only existing when client # authentication is used). This can be used to import the certificates # into CGI scripts. # o StdEnvVars: # This exports the standard SSL/TLS related `SSL_*' environment variables. # Per default this exportation is switched off for performance reasons, # because the extraction step is an expensive operation and is usually # useless for serving static content. So one usually enables the # exportation for CGI and SSI requests only. # o OptRenegotiate: # This enables optimized SSL connection renegotiation handling when SSL # directives are used in per-directory context. SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire <FilesMatch "\.(cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory /usr/lib/cgi-bin> SSLOptions +StdEnvVars </Directory> # SSL Protocol Adjustments: # The safe and default but still SSL/TLS standard compliant shutdown # approach is that mod_ssl sends the close notify alert but doesn't wait for # the close notify alert from client. When you need a different shutdown # approach you can use one of the following variables: # o ssl-unclean-shutdown: # This forces an unclean shutdown when the connection is closed, i.e. no # SSL close notify alert is send or allowed to received. This violates # the SSL/TLS standard but is needed for some brain-dead browsers. Use # this when you receive I/O errors because of the standard approach where # mod_ssl sends the close notify alert. # o ssl-accurate-shutdown: # This forces an accurate shutdown when the connection is closed, i.e. a # SSL close notify alert is send and mod_ssl waits for the close notify # alert of the client. This is 100% SSL/TLS standard compliant, but in # practice often causes hanging connections with brain-dead browsers. Use # this only for browsers where you know that their SSL implementation # works correctly. # Notice: Most problems of broken clients are also related to the HTTP # keep-alive facility, so you usually additionally want to disable # keep-alive for those clients, too. Use variable "nokeepalive" for this. # Similarly, one has to force some clients to use HTTP/1.0 to workaround # their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and # "force-response-1.0" for this. # BrowserMatch "MSIE [2-6]" \ # nokeepalive ssl-unclean-shutdown \ # downgrade-1.0 force-response-1.0 </VirtualHost> </IfModule> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet sudo a2enmod ssl sudo a2ensite back-ssl sudo ufw allow 443/tcp sudo service apache2 restart123

작성일 :2021-04-08 15:53 / 조회수: 246회
  • <<
  • 1
  • >>

소개글

원포올 선임 연구원

Kshield Jr. 2기 인증생

Cyber Guardians 수료생

플러터 앱 개발 강사

플라스크 웹 개발 강사

LG 쿠버네티스 보조강사

멀티캠퍼스 악성코드 보조강사

멀티캠퍼스 쿠버네티스 보조강사

금융감독원 쿠버네티스 보조강사

<시스템 해킹 프로토스타> 저자

<안드로이드 앱 개발에 딱 맞는 플러터와 다트 입문> 저자

문의: reasley.com@gmail.com

Category

Project List

Percent

JustCat

TextCount

Weather

Percent

Percent