我正在编写应用程序,它每秒扫描目录,检查新文件,如果它们出现 - 通过POST请求发送它们并执行存档.假设可以出现在目录中的文件数量可以从10到100 - 我决定使用asyncio和aiohttp来同时发送请求.
码:
import os
import aiohttp
from aiohttp.client import ClientSession
BASE_DIR = '/path/to'
ARCHIVE_DIR = '/path/to/archive'
async def scan():
while True:
await asyncio.sleep(1)
for file in os.listdir(BASE_DIR):
if os.path.join(BASE_DIR, file).endswith('jpg'):
asyncio.ensure_future(publish_file(file))
async def publish_file(file):
async with ClientSession(loop=loop) as session:
async with session.post(url=url, data={'photo': open(os.path.join(BASE_DIR, file), 'rb')}) as response:
if response.status == 200:
await move_to_archive(file)
async def move_to_archive(file):
os.rename(os.path.join(BASE_DIR, file), os.path.join(ARCHIVE_DIR, file))
loop = asyncio.get_event_loop()
coros = [
asyncio.ensure_future(scan())
]
loop.run_until_complete(asyncio.wait(coros))
Run Code Online (Sandbox Code Playgroud)
所以,问题是:如果我要发送的请求的并发,这是一个很好的做法,协同程序添加到循环是这样的:asyncio.ensure_future(publish_file(file))?
我听说,该服务不应链接到控制器中的作用域变量,因为视图可以直接访问服务。但我想将范围变量绑定到服务中存储的数据,并且我希望该变量反映服务中的所有更改。我读过很多解决方法,其中大多数都被告知使用 $scope.$watch,如果我想从控制器观看服务数据。我写了一个简单的例子,没有使用 $scope.$watch ,它的工作原理与我想要的完全一样,但我绝对不确定,我可以使用这样的东西,还是这是一个不好的做法。我学习 Angular 大约 2-3 天,非常需要你的建议:
html:
<div ng-controller="TestController">
<p>Current value = {{ serviceData.getValue() }}</p>
<input type="text" ng-model="newValue">
<button ng-click="changeServiceData(newValue)">Change</button>
</div>
Run Code Online (Sandbox Code Playgroud)
模块.js
var app = angular.module('app', []);
Run Code Online (Sandbox Code Playgroud)
控制器.js
app.controller('TestController', function($scope, testService){
$scope.serviceData = testService.getPublicData();
$scope.changeServiceData = function(newValue){
testService.setValue(newValue);
}
});
Run Code Online (Sandbox Code Playgroud)
服务.js
app.factory('testService', function(){
var value = null;
return {
setValue: function(newValue){
value = newValue;
},
getPublicData: function(){
return {
getValue: function(){
return value;
}
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
总结一下,view 只能访问 getters。为了更新数据,我正在使用服务,我可以将其注入任何控制器中,并且服务中的所有更改都会反映在控制器和视图上。
更新: 我尝试像这样改变我的工厂:
app.factory('testService', function(){
var value = …Run Code Online (Sandbox Code Playgroud)