'AI(DeepLearning)' 카테고리의 다른 글
tensorflow 강좌5. linear regression (0) | 2018.07.18 |
---|---|
tensorflow 강좌4. 학습데이터 저장/복구 (0) | 2018.07.18 |
tensorflow 강좌2. 자료형 (0) | 2018.07.16 |
[tf] tensorflow 강좌1 로딩테스트 (0) | 2018.07.16 |
[tf] 더 복잡한 함수를 학습해보자 (0) | 2017.06.01 |
tensorflow 강좌5. linear regression (0) | 2018.07.18 |
---|---|
tensorflow 강좌4. 학습데이터 저장/복구 (0) | 2018.07.18 |
tensorflow 강좌2. 자료형 (0) | 2018.07.16 |
[tf] tensorflow 강좌1 로딩테스트 (0) | 2018.07.16 |
[tf] 더 복잡한 함수를 학습해보자 (0) | 2017.06.01 |
tensorflow 강좌4. 학습데이터 저장/복구 (0) | 2018.07.18 |
---|---|
tensorflow 강좌3. 데이터처리 (0) | 2018.07.18 |
[tf] tensorflow 강좌1 로딩테스트 (0) | 2018.07.16 |
[tf] 더 복잡한 함수를 학습해보자 (0) | 2017.06.01 |
[tf] unknown math polynomial function modeling (0) | 2017.06.01 |
tensorflow 강좌3. 데이터처리 (0) | 2018.07.18 |
---|---|
tensorflow 강좌2. 자료형 (0) | 2018.07.16 |
[tf] 더 복잡한 함수를 학습해보자 (0) | 2017.06.01 |
[tf] unknown math polynomial function modeling (0) | 2017.06.01 |
[tf] XOR tensorflow로 학습구현 (0) | 2017.05.23 |
+LIBCURL 라이브러리로 POST data 전송하기 또는 curl 커맨드로 전송하기
https도 가능함.
#include <curl/curl.h>
#include <syslog.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define CURLCMD "curl"
struct PostResult {
size_t size;
char* ptr;
};
void init_string(struct PostResult *s)
{
s->size = 0;
s->ptr = malloc(s->size + 1);
if(s->ptr == NULL) {
fprintf(stderr," malloc() fail\n");
exit(EXIT_FAILURE);
}
s->ptr[0] = 0;
}
#ifdef _CURL_LIB_
static size_t
WriteCallback(void* ptr, size_t size, size_t nmemb, struct PostResult *s)
{
size_t new_len = s->size + size * nmemb;
s->ptr = realloc(s->ptr, new_len + 1);
if(s->ptr == NULL) {
fprintf(stderr, "ralloc fail\n");
exit(EXIT_FAILURE);
}
memcpy(s->ptr + s->size, ptr, size*nmemb);
s->ptr[new_len] = 0;
s->size = new_len;
return size*nmemb;
}
#endif
int Post_Send(char* url, char* jsonMsg)
{
#ifdef _CURL_LIB_
int i=0;
CURL *curl=NULL;
CURLcode res;
#endif
char inmsg[1024]={0,};
struct PostResult repost;
int maxsize=0 ;
// cmdline method
#ifdef _CURL_CMD_
char inmsg2[1024]={0,};
char cmdline[4096]={0,};
char result[1024]={0,};
#endif
if(!url || !jsonMsg) {
return -1;
}
init_string(&repost);
memset(inmsg, 0, sizeof(inmsg));
maxsize = strlen(jsonMsg)>sizeof(inmsg) ? sizeof(inmsg) : strlen(jsonMsg) ;
memcpy(inmsg, jsonMsg, maxsize) ;
// CURL 라이브러리 방식
#ifdef _CURL_LIB_
curl = curl_easy_init();
if(curl)
{
const int timeout = 30000;
i = strlen(inmsg);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, inmsg);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(inmsg));
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout/1000);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &repost);
res = curl_easy_perform(curl);
if(CURLE_OK != res)
{
// server error
return 1;
}
if(repost.size > 1){
// 수신 데이터 주소 : repost.ptr
curl_easy_cleanup(curl);
return -1;
}else{
printf("error: %s\n", strerror(res));
curl_easy_cleanup(curl);
// server error
return 1;
}
curl_easy_cleanup(curl);
}
#endif
// CURL 커맨드 방식
#ifdef _CURL_CMD_
{
int contimeout=10 ; // secs
FILE *fp=NULL ;
int index=0 ;
int rbytes=0 ;
memset(inmsg2, 0, sizeof(inmsg2)) ;
q2dq(inmsg, inmsg2, sizeof(inmsg2)) ; // " -> \"로 변경하는 함수
snprintf(cmdline, sizeof(cmdline)-1, "%s --connect-timeout %d -s -d \"%s\" -k \"%s\"",
CURLCMD, contimeout, inmsg2, url) ;
fp = popen(cmdline, "r") ;
if ( fp==NULL ) {
// server error
}
else {
do {
rbytes=fread(result+index, 1, sizeof(result)-index-1, fp) ;
#ifdef _DEBUG
printf("rbytees=%d\n", rbytes) ;
#endif
if ( rbytes<=0 )
break;
index+=rbytes ;
} while(rbytes!=0 );
pclose(fp) ;
#ifdef _DEBUG
printf("rcved=%s\n", result) ;
#endif
if( strlen(result)>1 ){
// 수신 데이터 주소: result
} else {
strcpy(tqResult->result, "100") ; // server error
}
#ifdef _DEBUG
printf("success post request\n");
#endif
}
}
#endif
return 0;
}
일부 함수는 없지만 적절히 수정하면 사용할 수 있다.
예를 들어 보내는 데이터를 "submit=1" 이렇게 하면 POST 수신쪽에서는 php의 경우 $_POST["submit"] 으로 받을 수 있다.
form data가 아닌 raw data를 그대로 받으려면
$post_raw_data = file_get_contents("php://input") ;
이렇게 한다.
다른 예제)
https://curl.haxx.se/libcurl/c/post-callback.html
smart pointer 스마트포인터? (0) | 2018.07.19 |
---|---|
const pointer or pointer / int *const / int const * / const int * (0) | 2018.07.19 |
if or 비교시 어떤 식의 성공으로 진입했는지 구분 (0) | 2018.07.13 |
Numerics library (0) | 2018.06.21 |
Preprocessor (0) | 2018.06.20 |
+if or 비교시 어떤 식의 성공으로 진입했는지 구분
가끔 복수의 or 조건으로 진입한 경우, 어떤 식의 성공으로 왔는지 간단하게 구분이 필요할 수 있다.
다시 어떤 식인지 판단해줘야 하는데 귀찮은 작업이다.
어떤 식의 만족으로 먼저 들어왔는지 간단히 판단하려면... 다음과 같은 팁이 있다.
예를 들어, 입력값 조건 순서가
1. 길이가 3이상이거나
2. a로 시작하거나
3. z로 끝난다.
위 세 조건을 or로 하여 먼저 만족하는 것은 어떤 것인가를 판단.
string str="....." ;
int ret=0 ;
if ( (ret=1, str.length()>=3 ) ||
(ret=2, str.at(0)=='a') ||
(ret=3, str.at( str.length()-1)=='z') ) {
std::cout << " match. ret=" << ret << std::endl ;
} else std::cout << " no match. " << std::endl ;
결과는 다음과 같다.
str="12345" 인 경우 ret=1 (길이 조건)
str="ab" 인 경우 ret=2 (a로 시작)
str="kz" 인 경우 ret=3 (z로 끝)
str="abz" 인 경우 ret=1 (길이 조건, a로 시작, z로 끝. 앞의 조건부터 판단하므로 ret=1로 됨.)
const pointer or pointer / int *const / int const * / const int * (0) | 2018.07.19 |
---|---|
libcurl HTTP POST send 모듈/curl 커맨드 방식도 지원 (0) | 2018.07.13 |
Numerics library (0) | 2018.06.21 |
Preprocessor (0) | 2018.06.20 |
deque (0) | 2018.06.13 |
+mysql에서 쿼리 결과를 변수로 저장하여 사용하기
Mysql 두 개의 테이블(또는 자신)에서 다른 값(불일치) 찾기 (0) | 2019.08.26 |
---|---|
[mysql] 쿼리시 스트링을 수타입으로 정렬하기 (0) | 2019.04.11 |
mysql select 한 데이터를 insert/update하기 (0) | 2018.07.12 |
only_full_group_by 에러 해결 (0) | 2018.07.04 |
그룹별 개수 조회 by 초 단위 (0) | 2018.05.30 |
Mysql 두 개의 테이블(또는 자신)에서 다른 값(불일치) 찾기 (0) | 2019.08.26 |
---|---|
[mysql] 쿼리시 스트링을 수타입으로 정렬하기 (0) | 2019.04.11 |
mysql 사용자 정의 변수 사용 (0) | 2018.07.13 |
only_full_group_by 에러 해결 (0) | 2018.07.04 |
그룹별 개수 조회 by 초 단위 (0) | 2018.05.30 |
mysql
+그룹별로 처음 나오는 하나의 줄만 뽑아낼때
ex) CAT_ID가 같은 것들끼리 묶어서 그룹별 처음으로 나온 레코드만 그룹 대표로 하나씩 추출한다.
select * from TABLE_A group by CAT_ID ;
그룹 내에서 어떤 키로 소팅하여 최신 값을 뽑는 경우, min, max 함수등을 이용하거나 미리 order by로 정렬 후 group by로 한다.
ex)
select * from (select * from TABLE_A order by NAME desc) a group by a.CAT_ID ;
select CAT_ID, min(NAME) from TABLE_A group by CAT_ID ;
+ group by 에러
only_full_group_by 에러가 발생.
=> mysql 5.7이상 부터 group by로 select 할 때 다른 값들이 있는 컬럼들을 조회하면 에러 발생.
처음 나온 것들을 자동으로 선택하여 조회하게 하려면 서버 설정을 바꿔주어야 한다.
/etc/mysql/my.cnf
[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
위와 같이 설정을 추가하여 서비스 재시작
service mysql restart
Mysql 두 개의 테이블(또는 자신)에서 다른 값(불일치) 찾기 (0) | 2019.08.26 |
---|---|
[mysql] 쿼리시 스트링을 수타입으로 정렬하기 (0) | 2019.04.11 |
mysql 사용자 정의 변수 사용 (0) | 2018.07.13 |
mysql select 한 데이터를 insert/update하기 (0) | 2018.07.12 |
그룹별 개수 조회 by 초 단위 (0) | 2018.05.30 |
랜덤스트링 만들기 (0) | 2019.03.22 |
---|---|
matplotlib subplot 화면분할 grid로 분할하기 (0) | 2019.03.22 |
WebAPI thread work status (0) | 2018.07.03 |
Python BeautifulSoup 웹크롤링/HTML 파싱. (0) | 2018.04.25 |
Python 데이터 저장/로딩 Pickle (0) | 2018.04.25 |
[Python에서 API서비스 구현하기]
POST로 JSON 요청받아 작업쓰레드를 돌려서 비동기 방식으로 작업하고,
진행 상태를 체크할 수 있는 구조.
Flask 사용.
- 구동 쉘 스크립트 ; server_run.sh
#!/bin/bash
/opt/anaconda3/envs/tensorflow/bin/python server_learn.py
- 서버 ; server_learn.py
from flask import Flask, request
from flask_restful import Resource, Api
from flask.views import MethodView
import json, base64
import string
import random
import os
import threading, time
app = Flask(__name__)
api = Api(app)
# 랜덤스트링 생성하는 함수. 세션키 생성 등
def random_string(size=6, chars=string.ascii_lowercase+string.digits):
return ''.join(random.choice(chars) for _ in range(size))
# 글로벌
g_bworking=False # 작업 여부.
g_progress = 0 # 진행 상태. 0~100
g_elapsedtime = 0 # 소요 시간. sec
g_workresult={} # 작업 결과
g_workname='' # 작업명
# 워커 쓰레드 ; 1~p1까지 sum구하기. 루프 돌때마다 p2 sec만큼 sleep.
def work(myid, p1, p2):
global g_bworking, g_progress, g_workresult, g_elapsedtime
starttime = time.time()
if g_bworking==True:
print('server is busy...')
return 0
g_bworking=True
g_workresult={}
g_progress=0
g_elapsedtime=0
total = 0
for i in range(1, (p1+1)):
total+=i
time.sleep(p2)
print('work : total[',myid,'] = ', total)
g_progress = 100* i / (p1)
g_elapsedtime = time.time() - starttime
endtime = time.time()
g_elapsedtime = endtime - starttime
g_workresult={'total':total, 'until':p1, 'sleep': p2}
g_progress=100
g_bworking=False
return total
class mysum(MethodView):
def get(self):
data = request.args
print(data) # dictionary
return {'name':'test'}
def options(self):
print('options.')
data = request.get_json() # application/json
print(data)
return {'Allow':'PUT,GET,POST'}, 200, \
{'Access-Control-Allow-Origin': '*', \
'Access-Control-Allow-Headers':'Content-Type,Authorization',\
'Access-Control-Allow-Methods': 'PUT,GET,POST'}
def post(self):
global g_workname
# data = request.form
# print(data) # dictionary
data = request.get_json() # application/json
print(data)
if g_bworking==True:
LearnResult = { 'result': 0 }
else:
num = int(data['num'])
slp = int(data['slp'])
g_workname = data['name']
t = threading.Thread(target=work, args=(g_workname, num, slp))
t.start()
LearnResult = {
'result': 1
}
return LearnResult
class status(MethodView):
def get(self):
data = request.args
print(data) # dictionary
if g_progress > 0 :
predtime = g_elapsedtime * 100 / g_progress
else:
predtime = 0
result = { 'work':int(g_bworking),
'workname':g_workname,
'progress':str(g_progress),
'workresult': g_workresult,
'elapsedtime':str(g_elapsedtime),
'remaintime': str(predtime - g_elapsedtime) }
return result
api.add_resource(mysum, '/mysum')
api.add_resource(status, '/status')
if __name__=='__main__':
app.run(host='0.0.0.0', port=18899, debug=True)
- 테스트
http://127.0.0.1:18899/mysum
POSTDATA ; 1~10까지 합 요청. 단계별로 1초씩 쉼.
{
"num": "10",
"slp": "1",
"name": "work1"
}
response: 즉시 아래와 같이 성공 리턴됨.
{
"result": 1
}
http://127.0.0.1:18899/status
GET
주기적으로 상태 체크 API 호출하여 결과 확인.
{
"workresult": {
"until": 10,
"total": 55,
"sleep": 1
},
"remaintime": "0.0",
"workname": "work1",
"elapsedtime": "10.011629581451416",
"work": 0,
"progress": "100"
}
matplotlib subplot 화면분할 grid로 분할하기 (0) | 2019.03.22 |
---|---|
File I/O, Directory list, read/write (0) | 2018.07.04 |
Python BeautifulSoup 웹크롤링/HTML 파싱. (0) | 2018.04.25 |
Python 데이터 저장/로딩 Pickle (0) | 2018.04.25 |
Python 커맨드라인 파싱 (0) | 2018.04.17 |